简体   繁体   中英

C++ Find Function Compile Error With std::string

I've been reading Stroustrup's "The C++ Programming Language" to learn how to program in C++, but the following example code from the text book doesn't seem to compile correctly.

#include <iostream>
#include <iterator>

int main()
{
 std::string s = "Hello!";
 char c = 'l';
 std::cout << "The number of " << c << "\'s in the string " << s << " is " << count(s,c);
}

int count(const std::string& s, char c)
{
    std::string::const_iterator i = std::string::find(s.begin(), s.end(), c);
    int n = 0;
    while(i != s.end())
    {
        ++n;
        i = std::find(i+1, s.end(), c);
    }

    return n;
}

These are the compile errors:

main.cpp:8:92: error: ‘count’ was not declared in this scope
      std::cout << "The number of " << c << "\'s in the string " << s << " is " << count(s,c);
                                                                                            ^
main.cpp: In function ‘int count(const string&, char)’:
main.cpp:13:80: error: no matching function for call to ‘std::basic_string<char>::find(std::basic_string<char>::const_iterator, std::basic_string<char>::const_iterator, char&)’
         std::string::const_iterator i = std::string::find(s.begin(), s.end(), c);

What is wrong with my code?

The first error tells you that when the compiler reaches main , it doesn't see any declaration for symbol count . This is one of the oddities of C and C++. To fix it, move the definition of count up, or merely declare its prototype before main .

The second error arises because you call the wrong function. From the arguments passed in, I guess you mean std::find rather than std::string::find . To get std::find , you also have to include the header <algorithm> .

count method is defined after main , so it is not visible in main . Either you have to define it before main , or you can forward declare count

int count(const std::string& s, char c) ;//forward declaration

int main()
{

  //code
}

int count(const std::string& s, char c)
{
 //code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM