I want to validate the input entered by the user, especially in case of int type..So that user should enter an integer value only not characters..
I found a solution given below, in one of the topics in this forum "Using cin to get user input" posted by "Zaita". But there is a problem with this code. If we enter input starting with an integer for example if we enter '34gf55' it takes the input as 34. I want that system should not take input if the input contain even a single character..
Please help....:)
// How to get a string/sentence with spaces
cout << "Please enter a valid sentence (with spaces):\n>";
getline(cin, input);
cout << "You entered: " << input << endl << endl;
// How to get a number.
int myNumber = 0;
while (true) {
cout << "Please enter a valid number: ";
getline(cin, input);
// This code converts from string to number safely.
stringstream myStream(input);
if (myStream >> myNumber)
break;
cout << "Invalid number, please try again" << endl;
}
cout << "You entered: " << myNumber << endl << endl;
// How to get a single char.
char myChar = {0};
while (true) {
cout << "Please enter 1 char: ";
getline(cin, input);
if (input.length() == 1) {
myChar = input[0];
break;
}