0

Input:

Today I eat bread. Today I eat cookies.

Output:

eat: 2
        
I: 2
        
Today: 2

bread: 1

cookies: 1

I have to make a program that counts the number of times that a word occurs in the input. Then if the number of times is equal between some words, then I display them in alphabetic order. Until now I did this:

#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int countt (string text);

int main () {
    string text;
    while (getline(cin,text))     //Receive the input here
    countt(text);                //Send the input to countt
    return 0;
}

int countt (string text) {
    int i,j;
    string aux;     //I make a string aux to put the word to compare here
        for (std::string::const_iterator i = text.begin(); *i != ' '; i++){
            for (std::string::const_iterator j = aux.begin(); j != text.end(); j++)
                *j=*i; //But here an error is given: 25:9: error: assignment of read-only location ‘j.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator*<const char*, std::basic_string<char> >()’
        }
        }

Many thanks in advance.

Community
  • 1
  • 1
Uaga
  • 41
  • 1
  • 5
  • Using debugger each time and trying to find source of the bug yourself will halp you become a *self-sufficient programmer*. In contrast, asking for help each time you get an error will degrade your *problem solving abilities*. – Ivan Aksamentov - Drop Mar 01 '14 at 16:36

2 Answers2

1

Referring specifically to the error comment you have in your code:

In your for loop you're using a const_iterator and then you're dereferencing that iterator and assigning to it, which you're not allowed to do because it's const.

Try again with string::iterator.

Eugene S
  • 3,092
  • 18
  • 34
0

Read a line into a string, much like you do now. But then use std::istringstream to tokenize the input. Use std::unordered_map to store the words as keys and the count as data.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • How do I use istringstream? I looker up but I don't understand very well how can I use it here.. – Uaga Mar 04 '14 at 00:43