0

If I prompt the user to enter an integer but what if the user enters a char or a string. How to prompt the user to enter in the correct data type?

#include<iostream>
using namespace std;

int main(){

     int num;

     cout<< "Enter number: ";
     cin>> num;

}
  • First you need to check if the input operation succeeded or failed. This can be done with a simple check like `if (cin >> num) { /* Success */ } else { /* Failure */ }`. The second thing you need to do is to [ignore](https://en.cppreference.com/w/cpp/io/basic_istream/ignore) the current input to the end of the line, if the input fails. The third thing is to [clear](https://en.cppreference.com/w/cpp/io/basic_ios/clear) the failed state of the input stream, if the input failed. And lastly, if the input failed you need to retry it, for example by using a loop. – Some programmer dude Jul 06 '22 at 11:05
  • In general, best is to get input as string/line, and then try to convert it to the appropriate type, then in case of failure print some message. – Jean-Baptiste Yunès Jul 06 '22 at 11:06
  • A tip for handling input and validation: Do it in a separate function, to not clutter up the rest of the code. – Some programmer dude Jul 06 '22 at 11:07

0 Answers0