I want to check if the input is valid, but when i do run this code I see that it checks only input for charcters. If i input a float number it will take it and going t
The code below should be able to do what you are hoping to achieve:
#inclide
using namespace std;
int n;
cout << "Your input is: "<> n) || cin.get() != '\n') {
cout << "Error. Number of elements must be integer. Try again: " << endl;
cin.clear();
cin.ignore(256, '\n');
}
The program asks the user to re-enter an integer if either of the following happens:
std::cin
stream. (For example, when a character or string is entered by the user)std::cin
is not the new line '\n'
character. (For example, when a number with a decimal point like 1.1
is entered, or when an integer followed by a character like 1a
is entered.)