使用std :: string查找函数编译错误

时间:2014-05-20 15:10:40

标签: c++ string find

我一直在阅读Stroustrup" The C ++ Programming Language"学习如何用C ++编程,但是教科书中的以下示例代码似乎没有正确编译。

#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;
}

这些是编译错误:

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);

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:3)

第一个错误告诉您,当编译器到达main时,它没有看到符号count的任何声明。这是C和C ++的一个奇怪之处。要解决此问题,请移动count的定义,或仅在main之前声明其原型。

出现第二个错误是因为您调用了错误的函数。根据传入的参数,我猜你的意思是std::find而不是std::string::find。要获得std::find,您还必须包含标题<algorithm>

答案 1 :(得分:2)

count方法是在main之后定义的,因此在main中不可见。您必须在main之前定义,或者您可以转发声明 count

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

int main()
{

  //code
}

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