C++ Primer 用Ctrl+Z退出 while (cin >> word) 的正確寫法

C++ Primer 中按照書中教程,while (cin >> word)無論如何也不能正常退出。如下簡單修改程序後,可用Ctrl+Z+回車鍵退出,且不影響寫入word的內容。

#include <vector>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    string word;
    vector<string> text;
    while (cin >> word)
    {
        text.push_back(word);

        //以下兩行爲添加內容
        if (word == "^Z")
            break;
    }
    for (auto& str : text)
    {
        cout << str << ",";
    }

    system("pause");
    return 0;
}

如果用 if (word == "XX")檢測輸入其他內容(XX)用於跳出while (cin >> word)的話,XX也會被寫入word中,但用Ctrl+Z輸入"^Z"的話,"^Z"並不會被寫入到word中(具體原因未知,可能是因爲EOF的特殊性)。注意輸入Ctrl+Z後仍需要按下回車鍵。

 

注:錯誤之處,敬請雅正!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章