Make sure the string is not a number before converting it to int

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); //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 string to the console if the string is not a number.

+4
source share
3 answers

, int , fail() :

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;
}

.

+3

, float, boost::lexical_cast<double>(mystr);, , float.

0

This will add a bit of your code, but you can parse mystr with isdigit from cctype. Library functions here . isdigit (mystr [index]) will return false if this character in the string is not a number.

0
source

All Articles