如何修复对strstr没有匹配函数调用的问题

How to fix no matching function call to strstr

本文关键字:函数调用 问题 何修复 strstr      更新时间:2023-10-16

所以我一直收到这个错误,对'strstr(str::string&, const char [2])' 的调用没有匹配函数

我已经看到了一些通过添加.str().c_str(); 来修复它的方法

但这对我来说似乎很棘手。对于我给定的场景,有没有一种更标准的方法:

 string resistance = stockIterator->getValue()->getOther();
                 if(strstr(resistance, "R")){
                    printf("Small resistance");
                    float first = atoi(strtok(resistance, "R"));
                    float second = atoi(strtok(NULL, " n"));
                    second = second/10;
                    float num = (first+second)/1000000;
                    num = num * stockIterator->getValue()->getStockCount();
                    printf(" %.7fnn", num);
                    count = count + num;

您确实应该使用std::stringfind()成员函数。要获得子字符串,可以使用std::stringsubstr()成员函数,而对于浮点转换,可以使用std::stof()。以下是您的操作方法:

string resistance = stockIterator->getValue()->getOther();
std::string::size_type pos = resistance.find("R");
if(pos != std::string::npos) {
    float first = std::stof(resistance.substr(0, pos));
    float second = std::stof(resistance.substr(pos+1));
    // other code 
}

这不是"hacky"—std::string::c_str()为您提供C++字符串的C字符串表示,如果您要混合C++字符串和C库函数(如strstr),这是您仅有的选项。

我给你最好的建议是停止在C++中使用C库函数。您应该使用std::string::find来查找std::string中的字符'R'

使用std::string::find
strstr适用于C字符串