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!

2
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by Ancient Dragon

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);
}``````

Edited by Ancient Dragon: n/a

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,

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.