4

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();
}
user1685094
  • 57
  • 1
  • 5
  • Last I checked, C++ did not have the `and` operator... – nneonneo Sep 20 '12 at 07:16
  • 1
    @nneonneo: No, [it does](http://en.cppreference.com/w/cpp/keyword/and). – Jesse Good Sep 20 '12 at 07:17
  • "and" is just another way of writing &&, should work on any modern compiler – user1685094 Sep 20 '12 at 07:19
  • Coool. Thanks all for pointing this out. Is && still preferred, though? This is really the first time I've ever seen it in code. – nneonneo Sep 20 '12 at 07:25
  • 1
    @nneonneo: The answer to your question can be found [here](http://stackoverflow.com/questions/2376448/the-written-versions-of-the-logical-operators), they shouldn't be used and basically they exist for keyboards that didn't have `&`, etc. – Jesse Good Sep 20 '12 at 07:35

1 Answers1

6

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.

std::basic_istream::get

jrok
  • 54,456
  • 9
  • 109
  • 141