Separating a String into Integers

Nov 22, 2013 at 12:56am
Hello. I have a string that the user will enter. Assume the user is not destructive or that I have set up the proper statements so it is input correctly. I need it to be separated into individual integer elements of an array. I know how to use an array and string, I just don't know the keywords for taking each digit and making it its own integer. Any help would be greatly appreciated. Thank you!
Nov 22, 2013 at 12:58am
closed account (Dy7SLyTq)
do you mean read in a string that is full of numbers (ie "1020904390358943093058930589462833") and read each digit into an array of type int?
Nov 22, 2013 at 2:06am
1
2
3
for (unsigned int i = 0; i < s.size(); i++) {
	cout << atoi( s.substr(i, 1).c_str() );
}


Note that atoi() returns 0 if it fails. stoi() in c++11 is of modern with exceptions and everything, but unfotunately I can't use it, because mingw 4.8.1 doesn't support it.

As most of my tasks have to do with streams anyway, I usually check the validity with
(stringstream_object >> int_number).fail(). isdigit() checks one character for its "digitness".

Hope it helps.

BTW: Users are destructive and they blame you for it, and they do misunderstand statements. Ever heard of the "any key anecdote"?
Last edited on Nov 22, 2013 at 2:10am
Topic archived. No new replies allowed.