【问题标题】:C++ Issue with cin and CTRL + Zcin 和 CTRL + Z 的 C++ 问题
【发布时间】:2014-11-04 03:58:06
【问题描述】:


我正在阅读 C++ Primer 5th,我在练习中遇到了一点问题:

从 cin 中读取一系列单词并将值存储为向量。后 您已经阅读了所有单词,处理了向量并将每个单词更改为 大写。打印转换后的元素,一行八个字。

我的代码是这样的:

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

using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;

int main(){

    vector<string> words;
    string wordBuffer;
    vector<string> output(1);

    while (cin >> wordBuffer){
        words.push_back(wordBuffer);
    }

    for (string &word : words){
        for (char &letter : word){
            letter = toupper(letter);
        }
    }

    unsigned currentLine = 0;
    for (decltype(words.size())index = 0; index < words.size(); ++index){

        output[currentLine] += words[index] + " ";

        if ((index+1) % 8 == 0){
            ++currentLine;
            output.push_back("");
        }

    }

    for (string s : output){
        s[s.size() - 1] = 0; //removing the whitespace
        cout << s << endl;
    }

    system("pause");
    return 0;
}

现在,一切正常,但我在控制台输入单词时遇到问题。
如果我写

我正在写一个随机的单词^Z

然后按 Enter 没有任何反应。按下 Enter 后,我必须重写 ^Z,如下所示:

我正在写一个随机的单词
^Z

你能解释一下为什么吗?谢谢!

PS:我这么说是因为在我之前的程序中,在同一行中写 ^Z 效果很好。就像在这段代码中一样:

#include <iostream>;


int main(){
    int currval = 0,val = 0;

        int count = 1;
        while (std::cin >> val){
            if (currval == val){
                ++count;
            }
            else {
                std::cout << "The number " << currval << " appears " << count << " times" << std::endl;
                currval = val;
                count = 1;
            }
        }
        std::cout << "The number " << currval << " appears " << count << " times" << std::endl;

    system("pause");

    return 0;
}

我不知道为什么:(

【问题讨论】:

  • 你是写^Z还是按Ctrl+Z? (在另一个程序中)
  • 这不是 C++ 问题,而是 Windows 中的标准行为。要确认您可以运行这个简单的程序并获得相同的行为(CTRL+Z 必须在其自己的行上按下才能终止):char c; while((c = getchar()) != EOF) putchar(c);

标签: c++ windows eof cin


【解决方案1】:

^Z 必须是第一个,以便 Windows 将其视为 Ctrl+Z,否则它只会被视为无意义的字符。

如果你希望它像你写的那样工作,我建议:

String wordBuffer("")
while (strcmp(wordBuffer[strlen(wordBuffer)-3], "^Z") != 0){
    words.push_back(wordBuffer);
    cin >> wordBuffer
}

EDIT: 在您的第二个示例中,它可以工作,因为当您读取整数时,c++ 知道将给定的数字字符串除以空格(如果输入了数字,则为 ENTER分别在每一行中)分别读取每个数字,因此如果您输入:

123 2323 4545 43 ^Z

它将读取 123,然后是 2323,...,然后是 ^Z,所以它就像它在单独的行中一样,但是当您读取字符串时,它不能这样做,因为字符串包含每个符号等等它将 ENTER 中的输入分开,这就是第二个起作用的原因

【讨论】:

  • 那么为什么在我的第二个示例中它有效?这是我无法理解的事情
  • 对于文本模式下的磁盘文件,CRT 的 _read 将 CTRL+Z (0x1A) 视为 EOF -- 无论位置如何。如果标准输入或cin 是一个文件,就是这种情况。如前所述,对于控制台,如果第一个字节是 CTRL+Z,则实际上是 Windows ReadFile 报告 0 个读取字符。
【解决方案2】:

据我所知 Ctrl+Z 在任何其他输入符号之前放置在键盘缓冲区中。因此,在 Ctrl+Z 之前输入的任何字符都将被丢弃。您需要执行以下操作

I am writing a random words  ENTER
^Z ENTER

【讨论】:

    猜你喜欢
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多