Reputation: 115
I wanted to validate a string that will be inputted by the user which follows two conditions. The condition would be whether the string is empty or the string has a space char. My current problem is that I can validate the string but it would require me to press enter once more time to reiterate my question "2. Enter Product Name: ".
while (true) {
cout << "2. Enter Product Name: ";
if(getline(cin, newNode->product_name)) {
if ((newNode->product_name).empty() || (newNode->product_name) == " ") {
cout << "Please enter a valid product name!\n";
cin.clear();
cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
}
else {
break;
}
}
}
Upvotes: 0
Views: 137
Reputation: 75062
Being inside the if
statement if(getline(cin, newNode->product_name)) {
means that the reading of a line succeeded. Therefore, you don't need the lines
cin.clear();
cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
They will request an extra line to ignore, so remove that lines.
Upvotes: 2