954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read number from string (mix of char and number)

Hi!

I've been searching for reading number in a string containing mix of number and char for hours, but I've found the right code. The string has the format

q23 - q3 (or q23-q3)

I'd like to read the number '23' and store it in x, '3' --> y, and '-' --> z. Could you tell me how to do this?
Thanks!

Tommy2010
Newbie Poster
2 posts since Feb 2010
Reputation Points: 10
Solved Threads: 0
 

There are several ways to do it. One way is to parse the string one character at a time. Something like this (Note: This was not compiled or tested, so use it at your own risk).

This does not solve your entire problem -- it just gets the numeric data. Your program will have to do something else to extract the math operator '-', '+', '*' and '/'. If you understand the code I am posting here then extracting the math symbol should not be a problem for you.

char* GetInt(char* str, int& n)
{
    n = 0;
    // skip over all non-digit characters
    while(*str && !isdigit(*str) )
         ++str;
    // convert all digits to an integer
    while( *str && isdigit(*str) )
    {
         n = (n * 10) + *str - '0';
         ++str;
    }
    return str;
}

int main()
{
    char* str = "q23 - q3 (or q23-q3)";
    int x,y,z;
    str = GetInt(str,x);
    str = GetInt(str,y);
    str = GetInt(str,z);
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Hi Ancient Dragon! Thanks for your reply. I've found in other place following way of doing this.

float a , b;
char v , op;

stringstream ss("v2.2- v3.3");

ss >> v >> a >> op >> v >> b;
-----
after running this, a = 2.2, b=3.3, op = '-'

And it works for me.
Thanks,

Tommy2010
Newbie Poster
2 posts since Feb 2010
Reputation Points: 10
Solved Threads: 0
 

glad you found a solution. You didn't say that the numbers could be floats.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You