no match for 'operator+' with std::string::operator+

I wrote this code for a small word counting algorithm:

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
#include <iostream>
#include <string>

int wordCount(const std::string&);

int main()
{
    std::cout<<wordCount("Hi there")<<std::endl;
    return 0;
}

int wordCount(const std::string& paragraph)
{
    std::string::iterator   iterator;
    bool                    iteratingOverWord       = false;
    int                     numberOfWords           =0;


     for(iterator = paragraph.begin();iterator<paragraph.end();iterator++)
     {
         if(isalnum(*iterator))
         {
             if(!iteratingOverWord)
             {
                 numberOfWords++;
                 iteratingOverWord = true;
             }
         }
         if(*iterator == ' ')
            iteratingOverWord = false;

     }
     return numberOfWords;
}


I get a problem while initialising the iterator inside the for loop. I've printed the error I get below:


wordCount.cpp: In function ‘int wordCount(const string&)’:
wordCount.cpp:19:37: error: no match for ‘operator=’ in ‘iterator = (& paragraph)->std::basic_string<_CharT, _Traits, _Alloc>::begin [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>, std::basic_string<_CharT, _Traits, _Alloc>::const_iterator = __gnu_cxx::__normal_iterator<const char*, std::basic_string<char> >, typename _Alloc::rebind<_CharT>::other::const_pointer = const char*]()’
wordCount.cpp:19:37: note: candidate is:
/usr/include/c++/4.6/bits/stl_iterator.h:702:11: note: __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >& __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >::operator=(const __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >&)
/usr/include/c++/4.6/bits/stl_iterator.h:702:11: note: no known conversion for argument 1 from ‘std::basic_string<char>::const_iterator {aka __gnu_cxx::__normal_iterator<const char*, std::basic_string<char> >}’ to ‘const __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >&’


I have no idea what that's trying to say and an internet search for similar problems was unhelpful. I'd really appreciate your help, thanks.
Last edited on
You need to use a const_iterator to iteratate over a const string.
std::string::const_iterator iterator;
Last edited on
That worked, and I understand my fault, I think: I need a const_iterator to iterate over a const std::string?
Topic archived. No new replies allowed.