3

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.

Qwertie
  • 5,784
  • 12
  • 45
  • 89

3 Answers3

3

You can find out if a read of an int has been successful or not by checking the fail() bit of your input stream:

getline (cin,mystr); //gets user input
stringstream priceStream(mystr);
priceStream >> price;
if (priceStream.fail()) {
    cerr << "The price you have entered is not a valid number." << endl;
}

Demo on ideone.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

If your want to check if the price user inputs is a float, you can use boost::lexical_cast<double>(mystr);, if it throws an exception then your string is not a float.

jfly
  • 7,715
  • 3
  • 35
  • 65
0

It's going to add a bit to your code, but you can parse mystr with isdigit from cctype. The library's functions are here. isdigit(mystr[index]) will return a false if that character in the string isn't a number.