验证输入和 getline() 函数

Validating input and getline() function

所以我想验证用户只输入了文本而不是数字。如果输入任何数字,然后我再次要求她输入。我认为这可以解决问题,但它似乎不起作用:

#include <iostream>

using namespace std;

int main()
{
    string name = "";

    cout << "Enter name: ";
    getline(cin, name);

    while (!cin) // or cin.fail()
    {
        cout << "Numbers are not allowed, input name again: ";
        cin.clear();
        cin.ignore(1000, '\n'); // is this even necessary since getline() already consumes spaces and new lines?
        getline(cin, name);
    }
}

因为name变量是string类型的,所以cin对象在接收数字时不应该失败吗?我如何验证它并确保它在输入数字时再次提示输入?另外,出于好奇,因为我已经在问了,如果用户输入类似:Scarlett9356 的内容,那么重新提示正确输入的好方法是什么?谢谢。

Because the name variable is of string type, shouldn't the cin object fail when it receives a number?

没有。由数字组成的输入也作为字符串有效。

您需要使用不同的策略来使其成为无效输入。

我会建议以下内容:

bool is_valid_input(std::string const& name)
{
   bool is_valid = true;
   // Figure out the logic for deciding when the input is not valid.

   // ...

   if (!is_valid )
   {
      cout << "Numbers are not allowed, input name again: ";
   }

   return is_valid;
}

int main()
{
    string name = "";

    do
    {
       cout << "Enter name: ";
       getline(cin, name);
    }
    while ( !is_valid_input(name) );
}

如果你想将你的输入限制为只接收没有数字的字符串,那么你可以使用 std::any_of and std::isdigit

std::string name = "";

std::cout << "Enter name: ";
std::getline(std::cin, name);

while (std::any_of(name.begin(), name.end(), [](char ch) { return std::isdigit(ch); }))
{
    std::cout << "Numbers are not allowed, input name again: ";
    std::getline(std::cin, name);
}

您可以通过这样做来验证您的字符串中没有数字:

#include <iostream>

using namespace std;

bool validName(string name)
{
    if(name.length() == 0)
        return false; // `name` cannot be empty

    for(int i = 0; i < name.length(); i++)
        if(name[i] >= '0' && name[i] <= '9') 
            return false; // There is a number in `name`

    return true; // `name` is valid
}

int main()
{
    string name = "";

    cout << "Enter name: ";
    getline(cin, name);

    while (!validName(name))
    {
        cout << "Numbers are not allowed, input name again: ";
        cin.clear();
        cin.ignore(1000, '\n'); // is this even necessary since getline() already consumes spaces and new lines?
        getline(cin, name);
    }
}