使用cin和CTRL+Z的C++问题

C++ Issue with cin and CTRL + Z

本文关键字:C++ 问题 CTRL+Z cin 使用      更新时间:2023-10-16


我正在读c++初级读本第五册,我对一个练习有点问题:

读取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后,我必须重写^Z,如下所示:

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

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

附言:我这么说是因为在我以前的程序中,在同一行写^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必须是第一个,Windows才能将其视为Ctrl+Z,否则它将被视为无意义的字符。

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

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

编辑:在您的第二个例子中,它之所以有效,是因为当您读取整数时,c++知道要将空间中给定的数字字符串除以(或者如果每行中单独输入数字,则ENTER),以单独读取每个数字,因此如果您要输入:

123 2323 4545 43 ^Z

它将读取123,然后是2323。。。然后^Z,就好像它在一个单独的行中得到了它,但当你读取字符串时,它不能做到这一点,因为字符串包含每个符号,所以它在按下ENTER时分离了输入,这就是为什么第二个工作

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

I am writing a random words  ENTER
^Z ENTER