0

I have this code:

double input2;
cout<<"please enter one number:"<<endl;
cin>>input2;

How can I judge if the user input only about digits, like '3', '4', or '4.241'. Sometimes when users enter a character like 'n', '3.q', my program will crash.

1

4 Answers 4

2

You can use stringstream to convert a string safely to number:

 string input;
 int mynumber;    
 cout << "Please enter a valid number: ";
 getline(cin, input);

   // This code converts from string to number safely.
   stringstream myStream(input);
   if (myStream >> myNumber)
    cout <<"number is valid"<<endl;
   else
    cout<<"invalid number";
Sign up to request clarification or add additional context in comments.

1 Comment

you can find this code at this link on official cplusplus reference site:
1

cin::<< operator returns NULL if operation went bad. Causes may be many but if interpretation fails then the failbit is set. You can check it with rdstate():

int main()
{
  double input2;
  cout<<"please enter one number:" << endl;

  cin >> input2;

  if (cin.rdstate() & ifstream::failbit)
     cout << "input badly formatted" << endl;

  return 0;
}

Comments

0

It won't crash because of that. If the cin >> input2 operation fails because of invalid input, cin is put in an invalid state, but it won't crash.

Comments

0

You need to verify that the input was auccessful

if (std::cin >> input2) {
    ...
}

.. and if it wasn't deal with the erronous input, e.g.:

std::cin.clear();
std::cin.ignore();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.