使用cin和CTRL+Z的C++问题
C++ Issue with cin and CTRL + Z
我正在读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
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题