【发布时间】: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);