2013-07-28 31 views
0

當我只是按下回車鍵而沒有輸入任何東西時,getline()函數也會收到空白輸入。如何解決它不允許空白輸入(有字符和/或數字和/或符號)?如何通過使用getline()來避免空白輸入?

string Keyboard::getInput() const 
{ 
    string input; 

    getline(cin, input); 

    return input; 
}  
+1

調用'getline'在一個循環,直到你得到有效的輸入。 – jamesdlin

回答

3

你可以繼續再這樣做,則對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; 
} 
+1

EOF呢?循環是不正確的IMO。 – Hiura

2

試試這個:

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