gpt4 book ai didi

C++ 程序不会通过字符串输入的 cin 步骤

转载 作者:搜寻专家 更新时间:2023-10-31 01:23:22 24 4
gpt4 key购买 nike

我显然没有完全理解 C++ 的“文件结束”概念,因为下面的程序没有通过“while (cin >> x)”步骤。每当我从命令行运行它时,它就坐在那里 mock 我。

通过 SO 和其他地方进行搜索时,很多人都提到了按 ctrl-z 然后按 enter 以在 Windows 上输入文件结束字符,但这似乎对我不起作用。这让我假设我的问题在别处。也许将 x 定义为字符串是我的错误?任何关于我在这里哪里出错的建议都会很棒。

注意:很抱歉代码中缺少注释——程序本身应该接受一系列 单词,然后吐出每个单词的计数。

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>

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

int main()
{
cout << "Enter a series of words separated by spaces, "
"followed by end-of-file: ";

vector<string> wordList;
string x;
while (cin >> x)
wordList.push_back(x);

typedef vector<string>::size_type vec_sz;
vec_sz size = wordList.size();
if (size == 0) {
cout << endl << "This list appears empty. "
"Please try again." << endl;
return 1;
}

sort(wordList.begin(), wordList.end());

cout << "Your word count is as follows:" << endl;
int wordCount = 1;
for (int i = 0; i != size; i++) {
if (wordList[i] == wordList[i+1]) {
wordCount++;
}
else {
cout << wordList[i] << " " << wordCount << endl;
wordCount = 1;
}
}
return 0;
}

最佳答案

如果你在 Windows 上,^Z 必须作为换行符后的第一个字符,如果你在 unixy shell 上,那么你想输入 ^D。

关于C++ 程序不会通过字符串输入的 cin 步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1561536/

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