2017-12-02 279 views
0

我想獲得用戶輸入,直到CTRL-D被擊中。如果我是正確的,控制d發出一個EOF信號,所以我試着檢查cin.eof()是否爲true,但沒有成功。C++停止詢問輸入在CTRL-D

這裏是我的代碼

string input; 
cout << "Which word starting which year? "; 
while (getline(cin, input) && !cin.eof()) { 
    cout << endl; 
    ... 
    cout << "Which word starting which year? "; 
} 

回答

4

所以,你想讀的,直到EOF,這是通過簡單地使用while循環和函數getline實現:

std::string line; 
while (std::getline(std::cin, line)) 
{ 
    std::cout << line << std::endl; 
} 

這裏使用getline(函數getline返回流)你得到的輸入,如果你按Ctrl+D,你擺脫了while循環。

重要的是要注意,EOF在Windows和onLinux上的觸發方式不同。您可以使用CTRL+D(用於* nix)或CTRL+Z(用於Windows)從命令行模擬EOF。

+0

目前這樣做 –

+0

我的代碼工作正常在Linux上,而不是在Windows上...... – APorter1031

+0

然後將更新答案。 –