Character frequencies in a string

Hello, I've been a lurker here for a little and am now compelled to join because I need help with a problem I've been working on.

For my project, I am trying to write a program that gets a string input from the user and add all the characters to a map where the key value is the letter and the mapped value is the frequency. If the letter already exists (is repeated in string) then I want the mapped value (frequency) to increment by one. I'm really confused on how to use a lot of the map class functions work exactly. Reading the C++ reference pages has confused me further. My thought process while writing the code was to use the find function to see if a key exists, if it doesn't exist, insert a new element with frequency 1 or increment an existing key's mapped-value by 1. I'm really new to C++ so any advice would be appreciated. This is where I am so far (this is an excerpt, the rest of my program just displays the information in a formatted list):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <iomanip>
#include <map>
#include <string>
#include <cstdlib>

using namespace std;

int main( )
{
	map <char, int> letters;		
	map <char, int>::iterator iter;	
	string user_text;		
	
  do
	{
						
		cout << endl << "Please enter some text and press enter: ";
		getline( cin, user_text );
		
		
		for(unsigned int i = 0; i < user_text.size(); ++i)
		{	
			
			iter = letters.find(i);
			
			if(iter == letters.end())
			{
				letters[i] = 1;
			}
			else
			{
				letters[i]++;
			}
			
		
		}
		
Last edited on
1
2
3
4
for ( unsigned int i=0; i< user.text.size(); ++i )
{
   ++letters[user_text[i]] ;
}
Thank you! that did work, but I don't know why it worked, and I'd really like to know what I was doing wrong...
I'd really like to know what I was doing wrong...


Refer to the comments:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
		for(unsigned int i = 0; i < user_text.size(); ++i)
		{	

                        // search for the (character represented by the) number i in letters.
			iter = letters.find(i);
			
			if(iter == letters.end())
			{
                                // the number wasn't found, so add it and make the count 1.
				letters[i] = 1;
			}
			else
			{
                                // the number was found, so increase it's count.
				letters[i]++;
			}
		}


As you can see, you didn't refer to user_text anywhere in the body of your for loop.
Last edited on
Topic archived. No new replies allowed.