I have a terminal application that receives user input, stores it in a string, and then converts to int. The problem is that the user enters everything that is not the number with which the conversion occurs, and the script continues without any indication that the string has not been converted. Is there any way to check a string containing any characters without a digit.
Here is the code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string mystr;
float price=0;
int quantity=0;
cout << "Enter price: ";
getline (cin,mystr);
stringstream(mystr) >> price;
cout << "Enter quantity: ";
getline (cin,mystr);
stringstream(mystr) >> quantity;
cout << "Total price: " << price*quantity << endl;
return 0;
}
Just before the conversion here: stringstream(mystr) >> price;I want it to print a string to the console if the string is not a number.
source
share