stream string

I'm working on a project for class to make a kiosk for ordering items. One of my fellow students suggested a way to stop a user from inputting a Letter or otherwise into an int variable. Usually if someone does this, the command prompt just closes and so forth. What they suggested was a string stream, I understood how it worked, but the compiler had issues about converting a string to an int at the end.
Example piece of my code:

while (true) {
	cout << "How many " << colorArray[orderNum][0] <<"s do you want: ";
		getline(cin, input);
		stringstream myStream(input);
		if (myStream >> myNumber)
			break;
		cout << "Invalid number, please try again" << endl;
	}
colorQuantity[orderNum] = input;
input is a string, myNumber a number...
Yes, I need what the user inputs to be checked that it is a number, just without the "colorQuantity[orderNum] = input;" the number is left as a string and I need it as an integer, unless you can do mathematical problems with string, then I must be mistaken.
You already converted the string to a number...
ofc u can do mathematical actions with an string, but that won´t nescessarily give u back an number^^... (and is not what you want)...

you could use isdigit on the string´s single chars (data not c_str - unless u stop at the \0)... and if you find and non-numeric character, assume its an string with leading numbers and discard it, or take those numbers...

or you could simply do what you did above...

1
2
3
4
5
 myStream >> myNumber;
 if(myStream.fail())
{
         //No Number, handle the problem...
}

there is another variant i do not remember yet... but i suggest you to use one of above... (at least i would do it this way^^...
Last edited on
Topic archived. No new replies allowed.