Click here to Skip to main content
15,886,060 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i just started with maps.this is the code i tried to implement.when i take input for string.it keeps taking input but doesn't output the code.how can i modify this code so that i can get my required result.

What I have tried:

C++
#include<iostream>
#include<conio.h>
#include
#include<string>
#include<iterator>

using namespace std;

int main()
{
        map<string, int> stringCounts;
	string str;

	while (getline(cin, str)) 
          stringCounts[str]++;

	map<string, int>::iterator iter;
	for (iter = stringCounts.begin(); iter != stringCounts.end(); iter++)
	{
	cout << "word: " << iter->first << ", count: " << iter->second << endl;
	}
	_getch();
}
Posted
Updated 24-Apr-18 5:36am
v2
Comments
Richard MacCutchan 24-Apr-18 11:45am    
You need to tell it when there is no more input. Use ^Z at the console, or test for some special string.

1 solution

Actually your code (or a compiling version of it) works.
C++
#include <iostream>
#include <map>
#include <string>
#include <iterator>

using namespace std;

int main()
{
  map<string, int> stringCounts;
  string str;

  while (getline(cin, str))
    stringCounts[str]++;

  map<string, int>::iterator iter;
  for (iter = stringCounts.begin(); iter != stringCounts.end(); iter++)
  {
    cout << "word: " << iter->first << ", count: " << iter->second << endl;
  }
}

sample input:
as
asas
asas
aa

output
word: aa, count: 1
word: as, count: 1
word: asas, count: 2


[update]
The same program written using modern C++:
#include <iostream>
#include <map>

using namespace std;

int main()
{
  map<string, int> stringCounts;
  string str;

  while (getline(cin, str))
    stringCounts[str]++;

  for (auto p : stringCounts)
    cout << "word: " << p.first << ", count: " << p.second << endl;
}

[/update]
 
Share this answer
 
v3
Comments
Member 13784265 24-Apr-18 12:02pm    
it doesn't on my compiler.i'm using the same input as you did but it keeps asking for input
CPallini 24-Apr-18 17:21pm    
Because you have to input the EOF character (CTRL+Z on Windows) to exit the while loop.
Member 13784265 25-Apr-18 10:14am    
how can i check the frequency of each word in a string using the same technique ?
CPallini 25-Apr-18 14:12pm    
Split the string and insert the resulting words in the map.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900