我顯然不是很接近C++的'文件結束'概念,因爲下面的程序只是沒有越過「while(cin >> x) 「 步。每當我從命令行運行它時,它都會嘲笑我。C++程序沒有移動過去的字符串輸入cin步驟
通過SO和其他地方的搜索提供了很多提及點擊CTRL-Z然後點擊輸入在窗口上通過文件結束字符,但這似乎並沒有爲我工作。這讓我認爲我的問題在別處。也許把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;
}
肯定地發表一個新問題,對已經有一個可接受的答案的問題的評論中的後續操作不會獲得許多意見。 – 2009-10-13 18:50:20