Displaying and counting character problem

Good day to all just wanna ask regarding my program in C++, the problem is I need to enter a line of character/sentence and then it will count and display the number of each letter,white spaces and special character
the sample output is :good day to you!!
number of white space = 3
number of special character = 2
a=1
d=2
g=1
o=2
t=1
y=2
u=1

so far, all i have is this code im having a hard time in displaying the occurence of each letter,hope you could help me thanks


#include <iostream.h>
#include <conio.h>

void main()
{
clrscr();
int countch=countsc=countsp=0;
cout<<"please enter a sentence:"<<endl;
char ch='a';
while (ch!='\r')
{
ch=getche();
if (ch==' ')
countch++;
else
countch++;
if (ch=='!'||ch=='@'||ch=='#'||ch=='$'||ch=='&'||ch=='?')
countsc++;
}

cout<< "number of white space :" <<countsp <<endl;
cout<< "number of special character : " <<countsc <<endl;
getch();
}


finding the occurence of each letter is really simple.

1. Make a map<char, int> to track everything
2. Loop through the string and fill in the map.
.....Before adding anything to the map, check to see if the character you're trying to add already exists in the map. If it does, increment its value. Otherwise, add the char to the map with a value of 1.

this can be done like this
1
2
3
4
5
6
7
8
9
10
11
12
13
std::string theString;
std::map<char, int> charMap;
std::map<char, int> charMapItr;

for(str_sz i = 0; i < theString.size(); ++i)
{
	charMapItr = charMap.find(theString[i]);

	if(charMapItr == charMap.end())
		charMap.insert(make_pair(theString[i], 1));
	else
		charMapItr->second++;
}


http://cplusplus.com/reference/stl/map/
there's a reference for maps.

EDIT:
If you're using <iostream.h> your sources are outdated. Nowadays it's just <iostream>
and <conio.h> is platform dependant, i'd recomend not using it. Instead use the io functions provided in the stl. http://cplusplus.com/doc/tutorial/basic_io/
Last edited on
Topic archived. No new replies allowed.