String to Int

Im making a simple program that orders numbers from least to greatest. Is there a way for the user to enter all of his numbers and type "done" and the program will recognize it? I've only been using cout, and I try to store the numbers in a string and test it with an if statement, but i can't convert it to an integer in order to use the numbers in the program. Help?
I gotta admit I don't EXACTLY understand what you wanna do, but you can EITHER use atoi like this:

1
2
3
string a("45");
int b;
b = atoi(a.c_str());


or stringstreams like this (recommended):

1
2
3
4
5
string a("45");
int b;
stringstream ss;
ss<<a;
ss>>b;


In both cases, b will hold the value 45 afterwards.

Note: When using atoi, you will have to include <cstdlib>, when using stringstreams you have to include <stringstream>
Last edited on
<stringstream> isnt in the C++ directory...
@ OP: Yeah the part about storing the numbers in the string. Don't do that. I'd test the users input with isalpha(...) see here:
http://www.cplusplus.com/reference/clibrary/cctype/isalpha/
That way if his input is a number it returns false and you store it in your vector, if it is a letter, any letter, then you wrap it up and go to the next part of your program. It's just easier, you could go a step further and verify that the user actually DID enter "done" or any number of other commands you decide on later but that's something to worry about once you get rolling.

@ jakecodes: That's because "stringstream" is a class in "iostream", don't worry I had to look it up to make sure :P see here: http://www.cplusplus.com/reference/iostream/
Last edited on
I meant <sstream> anyways. stringstream was the old one.
@computergeek01
Tried your method, heres the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
int test;
	
	for(int i = 0;i<100;i++)
	{
	
	cin >> test;
	
	int check = isalpha(test);
	
	cout << check << endl;
	
		test = 0;
	}


when i type a number, it returns 0. when i type a letter, it returns 0's untill the loop is over. whats wrong with it?
You are trying to read into an int, so when you type a letter the extraction fails and cin goes into an error state. Make test a char intead.
but then the problem isn't solved. I need the variable to end up being an int. is there any way to do that?
Char's can be case to int's pretty easy http://www.cplusplus.com/doc/tutorial/typecasting/. It may take some processing but nothing too complicated.
isalpha() doesn't do any conversion. You want to use isalpha() to check that the string is valid, then use stringstreams to convert to a number.
Topic archived. No new replies allowed.