简体   繁体   中英

validate string input with while loop

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;
        }
    }
} 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM