2010-05-10 276 views
0

我有一個循環,我要求用戶輸入一個名稱。當用戶按下ENTER鍵時或當輸入20個名字時,我需要停止。C++檢測用戶按下的ENTER鍵

while(!stop && ind < 20) 

或:然而,當用戶按下ENTER鍵

//loop until ENTER key is entered or 20 elements have been added 
bool stop = false; 
int ind = 0; 
while(!stop || ind >= 20){ 

    cout << "Enter name #" << (ind+1) << ":"; 
    string temp; 
    getline(cin, temp); 
    int enterKey = atoi(temp.c_str());   

    if(enterKey == '\n'){ 
     stop = true;    
    } 
    else{ 
     names[ind] = temp; 
    } 

    ind++; 


} 

回答

4

你讀字符串轉換爲整數,atoi

int enterKey = atoi(temp.c_str());   

如果TEMP像"1234"這樣的字符串將enterKey設置爲1234。然後,您將enterKey\n的ASCII值進行比較。這很可能沒有做任何有用的事情。

std::getline只讀字符,但不包括,下一個'\n'。如果用戶只按下輸入而不鍵入任何其他字符,則std::getline將返回空字符串。如果字符串爲空,可以用它empty()方法容易測試:

getline(cin, temp); 
if (temp.empty()) { 
    stop = true; 
} 
+0

你是對的。這工作 – user69514 2010-05-10 15:13:08

2

試試我的方法不停止

using namespace std; 
vector <string> names; // edited. 
for (int ind = 0; ind < 20; ++ind) 
{ 
    cout << "Enter name #" << (ind+1) << ":"; 
    string temp; 
    getline(cin, temp); 
    if (temp.empty()) 
     break; 
    names.push_back(temp); 
} 
+2

其實這是一個混亂。有幾個錯誤... – 2010-05-10 14:50:07

+1

是的,我完全同意,'for'循環是要走的路。儘管你的代碼有一個錯誤。結果向量將有20個空字符串,然後是一些響應。 – Geoff 2010-05-10 15:03:35

+0

你遺漏了atoi步驟。你應該使用一個向量而不是向量 jmucchiello 2010-05-10 15:06:49

2

函數getline會吃你的分隔符,這將是「\ n',所以你可能想要檢查一個空字符串。在致電atoi之前做。

1

嘗試用stop = temp.empty()代替。 getline不應該包含任何換行符。一個空行應該導致一個空字符串。

此外,查爾斯是正確的,你的條件不正確,使用while(!stop && ind < 20)。用戶編寫的方式需要輸入20個值和一個空行。查爾斯的變化表明,只要符合任何一種條件(不是兩種),就會突破。

爲了完整起見,這裏所提出的新代碼:

bool stop = false; 
int ind = 0; 
while(!stop && ind < 20){ 

    cout << "Enter name #" << (ind+1) << ":"; 
    string temp; 
    getline(cin, temp); 
    if(temp.empty()) { 
     stop = true; 
    } else { 
     names[ind] = temp; 
    } 

    ind++;  
} 

就個人而言,我會寫出如下代碼:

vector<string> names; 
for(int ind = 0; ind < 20; ind++) { 
    cout << "Enter name #" << (ind + 1) << " (blank to stop): "; 
    string name; 
    getline(cin, name); 
    if(name.empty() || cin.eof()) { 
    break; 
    } 
    names.push_back(name); 
} 

cout << "Read " << names.length() << " names before empty line detected." << endl; 
+0

爲什麼不只是當temp.empty()時打破?那你就不需要其他結構啊 – jmucchiello 2010-05-10 15:03:42

+0

啊。是的。應該是<。我複製了它,錯過了那裏的錯誤。 – Geoff 2010-05-10 15:05:32

+0

你也忘了翻轉ind> = 20的條件。 – jmucchiello 2010-05-10 15:05:57

0

你想用cin.get(); cin >> temp;我相信。

+0

cin >> temp'只會給一個令牌。 OP可能需要包含空格的語句。 – Geoff 2010-05-10 15:10:56