【发布时间】:2018-01-22 12:45:44
【问题描述】:
我正在阅读 B. Stroustrup 的Programming Principles and Practice Using C++,在做其中一个练习时遇到了问题。我正在使用 Windows 10(我相信,这与此处相关)。 下面的代码应该向用户询问要打印的单词。但是,如果一个单词是“broccoli”,那么将打印“BLEEP”而不是“broccoli”。
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main()
{
string bad_word = "broccoli";
cout << "type in some words\n";
vector <string> words;
for (string temp; cin >> temp; )
words.push_back(temp);
cout << "There are " << words.size() << " words in vector 'words'.\n";
for (string word : words) {
if (word != bad_word)
cout << word;
else
cout << "BLEEP";
}
keep_window_open();
return 0;
}
所以,我让我的程序要求我输入单词,我打印一些,然后按 Ctrl+Z + Enter,但没有任何反应。如果我再次这样做,控制台将关闭。为什么不打印此行指定的字数?
cout << "There are " << words.size() << " words in vector 'words'.\n";
为什么我第二次按Ctrl+Z+Enter后程序就执行完了? 我想了解这里的问题到底是什么。 谢谢。
【问题讨论】:
-
这可能是因为您使用的 Visual Studio 行为有点奇怪。尝试使用 CTRL+F5 而不是 F5 来启动您的程序,看看是否有帮助。
-
CTRL+Z 发送到 linux 后台。 superuser.com/a/476875/459974(添加一些信息)您使用的是 Windows 10,那么这不是问题
-
您的
keep_window_open不起作用;cin在您的第一个循环之后已经处于“坏”(如 eof)状态,因此再次读取它是无效的。 (通常,您应该从终端启动控制台应用程序,不知道 windows 中的“新”应用程序叫什么,但如果您运行 powershell,它应该会打开) -
在 Linux 上,Cntrl+D 工作正常。
-
也许你应该在循环之后添加一个
cout << endl;,否则你的输出缓冲区可能不会被刷新