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();
}
5
  • Last I checked, C++ did not have the and operator... Commented Sep 20, 2012 at 7:16
  • 1
    @nneonneo: No, it does. Commented Sep 20, 2012 at 7:17
  • "and" is just another way of writing &&, should work on any modern compiler Commented Sep 20, 2012 at 7: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. Commented Sep 20, 2012 at 7:25
  • 1
    @nneonneo: The answer to your question can be found here, they shouldn't be used and basically they exist for keyboards that didn't have &, etc. Commented Sep 20, 2012 at 7:35

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.