简体   繁体   中英

Counting characters in words in a C++ console application

This is the problem that I am attempting to solve:

Ask the user to enter a bunch of words, as many as they want, until they enter a 0. After that, count how many times each letter appears across all the words, and print out a list of each letter and how many times it appears. Example:

Enter word> hello
Enter word> lemon
Enter word> goodbye
Enter word> 0
Letter: h appears 1 times
letter: e appears 3 times
...

So far I have to put all the words together, and have made comparisons. The problem lies in that, after all the words are put together, and 0 is input, I cannot count each invidual character within the combined string. I did some research, and I've read that to perform this you need vectors, but i do not understand how to use them.

I've been trying at it for a week to get it right, but to no avail. C++ is sort of different from all the other language I have learned (at least for me).

You can use an std::unordered_map , with the characters as key and the counter as value. For each string you read, just iterate over it and increase the value corresponding to the character in the map.

This way you don't actually need to store the words.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM