gpt4 book ai didi

cin 和 CTRL + Z 的 C++ 问题

转载 作者:可可西里 更新时间:2023-11-01 11:18:26 25 4
gpt4 key购买 nike


我正在阅读 c++ primer 5th,我在练习中遇到了一个小问题:

Read a sequence of words from cin and store the values a vector. After you’ve read all the words, process the vector and change each word to uppercase. Print the transformed elements, eight words to a line.

我的代码是这样的:

#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;
}

现在,一切正常,但我对控制台输入的文字有疑问。
如果我写

I am writing a random words ^Z

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

I am writing a random words
^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 必须在前面,以便 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 中的输入分开,这就是为什么第二个输入有效

关于cin 和 CTRL + Z 的 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25766486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com