【问题标题】:Console program stops execution after Ctrl+Z [duplicate]Ctrl + Z后控制台程序停止执行[重复]
【发布时间】: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 &lt;&lt; endl;,否则你的输出缓冲区可能不会被刷新

标签: c++ console-application


【解决方案1】:

ctrl-z 是文件结束信号。 这会禁用从输入流 (cin) 的读取。

因此,您的保持窗口打开功能立即返回而无需等待(因为无法读取),并且您的控制台关闭。

【讨论】:

    猜你喜欢
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    相关资源
    最近更新 更多