Why is the following C ++ program printing ascii strings instead of characters?

This program should store every word specified in the standard input stream and count their occurrences. Results should be printed afterwards, followed by their score. As far as I can tell, the program works differently, but the lines are printed as values โ€‹โ€‹of ASCII characters, not 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(); } 
+4
source share
1 answer

std::istream::get() does not return char , but std::ios::int_type (typedef for some integer type that can contain all char_type and EOF values), and this is what you insert into stringstream. You should direct the result to char .

std :: basic_istream :: get

+6
source

Source: https://habr.com/ru/post/1435208/


All Articles