about reading integers in a string

Sep 26, 2008 at 3:05pm
Hello, this is my first post here.
I want to ask how to read multiple integers in a string using atoi

for example
int main()
{
int a, b, c;
string str("111 222 333");
cout << "string = " << str << endl;

a = atoi (str);
b = atoi (str);
c = atoi (str);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;

return 0;
}

In this case, the output will be
string = 111 222 333
a = 111
b = 111
c = 111

However I want the output to be
string = 111 222 333
a = 111
b = 222
c = 333

Could anyone help me to modify the code to have the desired result?
Of course less modification is better.
Thanks for reading.
Sep 26, 2008 at 4:32pm
atoi isn't the right solution to the problem. Consider using strtol or strtoul instead.

The problem is that atoi( "111 222 333" ) will return 111 always. What you would
need to do is remove the "111" from the string and then call atoi again, ie,
atoi( " 222 333" ) will now return 222. How to remove the "111" from the string?
Well, look up strtol. It will give you a pointer to the first character in the string
that was not consumed by the previous conversion, ie, strtol on "111 222 333"
would return 111 and also give you a pointer to the space immediately after 111.
You could use that pointer and call strtol again to get 222, etc.
Sep 27, 2008 at 2:11am
Thanks for the reply first.
Actually there is another problem.
I have to read a string of number from a file,
so I have no idea how long the string will be.
The strtol example here uses char str[] as the string input.
However I have to use string str to ensure that I don't miss anything from every line the file.
How can the strtol example be modified to use string str instead of char str[]?
Sep 27, 2008 at 2:31am
Oh, I made it.
Thanks.
Topic archived. No new replies allowed.