top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to extract integers from a string using C or C++?

+2 votes
842 views
How to extract integers from a string using C or C++?
posted May 2, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

3 Answers

0 votes

If you pass an integer in string then it will be considered as a character not integer and value of 0 to 9 will be considered as an ASCII value of it 48 to 57 Respectively.

#include<stdio.h>
main()
{
char a[100],i;
printf("Enter a string: \n");
scanf("%s",a);
     for(i=0;a[i];i++)
     {
          if((a[i]>=48) && (a[i]<=57))
          printf("%c \n",a[i])
     }
}
answer May 4, 2015 by Chirag Gangdev
0 votes

Just modifying the logic of chirag a bit to cover the full integer return in place of just digit.

#include <stdio.h>

int main(void) {
    char *a="My 10a10 and 20";
    int abc, i, count;

    for(i=0;a[i];i++) 
    {
        if((a[i]>=48) && (a[i]<=57))
        {
            sscanf(&a[i], "%d", &abc);
            printf("%d\n", abc);

            // Get the digit count to adjust i 
            while(abc != 0)
            {
                abc/=10;             
                ++i;
            }
        }
    }

    return 0;
}
answer May 4, 2015 by Salil Agrawal
0 votes

int main() {

std::stringstream ss;
std::string input = "a b c 4 e";

ss.str("");
ss.clear();

ss << input;

int found;
std::string temp = "";

while(!ss.eof()) {
        ss >> temp;
        // if temp not an int
                ss >> temp; // keep iterating
        } else {
                found = std::stoi(temp); // convert to int
        }
}

std::cout << found << std::endl;

return 0;

}

answer Mar 10, 2016 by Ashish Kumar Khanna
Similar Questions
+1 vote

How to find first unrepeated character in string using C/C++?

Input       Output     
abc         a    
aabcd       b
aabddbc     c
0 votes

Find the first non repeating character in a string.

For example
Input string: "abcdeabc"
Output: "e"

0 votes

I am looking to reverse a string using binary search algorithm but no clue. Can someone share the algo and may be C/C++ code?

...