简体   繁体   English

使用 while 循环验证字符串输入

[英]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: ".我当前的问题是我可以验证字符串,但它需要我再次按 Enter 键来重申我的问题“2。输入产品名称:”。

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.if语句中if(getline(cin, newNode->product_name)) {意味着读取一行成功。 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.他们将要求忽略额外的行,因此请删除该行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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