Reputation: 57
This program is supposed to store each word given in standard input stream and count their occurences. The results are supposed to be printed afterwards in order followed by their count. As far as I can tell, the program is working otherwise, but the strings are printed as a ASCII values of the characters instead of the characters themselves. What's wrong?
#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();
}
Upvotes: 4
Views: 2770
Reputation: 55395
std::istream::get()
doesn't return a char
but std::ios::int_type
(a typedef for some integer type that can hold all values of char_type
and EOF) and that is what you insert in stringstream. You should cast the result to char
.
Upvotes: 6