将 cin 与 while 一起使用

using cin with while

大家好!我最近尝试了 [C++ Primer,第 5 版] 中的一段代码。此代码在第 3 章。

#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string word;
    while(cin >> word) {
        cout << word << endl;
    }
    return 0;
}

然后,这本书说:“...一旦我们到达文件末尾(或有效输入),我们就会退出。”令人惊讶的是,在 Visual Studio C++ 2017 中尝试此代码时,我永远无法从 while 语句中跳出。

我的问题是:给什么输入会跳出循环?这本书非常有名,很多人都看过,所以我相信代码没有错误。

谢谢!

在控制台中您可以模拟 EOF 标志。在 UNIX 系统中是 Ctrl+D,在 Windows 中是 Ctrl+Z。当您在控制台中键入此内容时,程序的行为就像刚刚到达输入文件的末尾一样。