【问题标题】:Error using strlen使用 strlen 时出错
【发布时间】:2014-11-14 01:30:50
【问题描述】:

我一直在查找有关如何使 strlen 工作的示例和教程,但没有任何工作。我正在制作一个小程序,让你输入你的句子,你可以搜索句子中的特定字母。

错误显示:

19:23: error: cannot convert âstd::string {aka std::basic_string<char>}â to âconst char*â for argument â1â to âsize_t strlen(const char*)â

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

int main() {
    char letter;
    string sentence;
    int count;

    cout << "Enter a character to count the number of times it is in a sentence: ";
    cin >> letter;

    cout << "Enter a sentence and to search for a specified character: " << endl;
    getline(cin, sentence);

    for(int i = 0; i < strlen(sentence); i++){
            if(sentence[i] == letter){
                    count++;
            }
    }
    cout << letter << " was found " << count << " times." << endl;
}

【问题讨论】:

  • strlen 函数适用于 C 风格的字符串,也就是 char *,不适用于 std::string。查看任何好的 C++ 参考中的函数声明和描述。

标签: c++ string strlen


【解决方案1】:

由于sentencestd::string,您应该使用sentence.length()strlen(sentence.c_str())

【讨论】:

  • sentence.size()(我更喜欢它,因为它与其他 C++ 库容器一致)。 strlen(sentence.c_str()) 不是一个好的选择,因为它可能会执行计算每次迭代的长度的工作。
猜你喜欢
  • 2013-01-03
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 2015-08-14
相关资源
最近更新 更多