簡體   English   中英

如何通過使用getline()避免空白輸入?

[英]how to avoid blank input by using getline()?

當我只按Enter鍵而不輸入任何內容時, 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 */
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM