0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.