如何使用getline()避免空白输入

how to avoid blank input by using getline()?

本文关键字:空白 输入 何使用 getline      更新时间:2023-10-16

当我只按回车键而没有输入任何内容时,getline()函数也会收到空白输入。如何修复不允许空白输入(有字符和/或数字和/或符号)?

string Keyboard::getInput() const
{
    string input;
    getline(cin, input);
    return input;
}    

只要输入为空,就可以继续重新执行getline。例如:

string Keyboard::getInput() const
{
    string input;
    do {
      getline(cin, input);    //First, gets a line and stores in input
    } while(input == "")  //Checks if input is empty. If so, loop is repeated. if not, exits from the loop
    return input;
}

试试这个:

while(getline(cin, input))
{
   if (input == "")
       continue;
}
string Keyboard::getInput() const
{
    string input;
    while (getline(cin, input))
    {
        if (input.empty())
        {
            cout << "Empty line." << endl;
        }
        else
        {
            /* Some Stuffs */
        }
    }
}