该程序应该存储标准输入流中给出的每个单词并计算它们的出现次数。结果应该按顺序打印,然后按顺序打印。据我所知,该程序正在工作,但字符串打印为字符的ASCII值而不是字符本身。怎么了?
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <cctype>
#include <algorithm>
std::string get_word();
int main()
{
std::vector<std::string> words;
std::string word;
while (std::cin.good()) {
word = get_word();
if (word.size() > 0)
words.push_back(word);
}
std::sort(words.begin(), words.end());
unsigned n, i = 0;
while (i < words.size()) {
word = words[i];
n = 1;
while (++i < words.size() and words[i] == word)
++n;
std::cout << word << ' ' << n << std::endl;
}
}
std::string get_word()
{
while (std::cin.good() and !std::isalpha(std::cin.peek()))
std::cin.get();
std::stringstream builder;
while (std::cin.good() and std::isalpha(std::cin.peek()))
builder << std::cin.get();
return builder.str();
}
答案 0 :(得分:6)
std::istream::get()
不会返回char
而是std::ios::int_type
(某个整数类型的typedef可以包含char_type
和EOF的所有值),这就是你在stringstream中插入。您应该将结果转换为char
。