I have got a terminal app that gets user input stores it in a string then converts it into a int. The problem is if the user inputs anything that is not a number the conversion fails and the script continues without any indication that the string has not converted. Is there a way to check of the string contains any non digit characters.
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); //gets user input
stringstream(mystr) >> price; //converts string: mystr to float: price
cout << "Enter quantity: ";
getline (cin,mystr); //gets user input
stringstream(mystr) >> quantity; //converts string: mystr to int: quantity
cout << "Total price: " << price*quantity << endl;
return 0;
}
Just before the conversion here: stringstream(mystr) >> price;
I want it to print a line to the console if the string is Not a Number.