“stoi”未在此范围内声明

问题描述 投票:0回答:3

我已经用另一种方式修复了它,但我仍然想知道为什么 stoi 在这里不起作用。这是代码:

#include <string>
#include<iostream>
std::string fakeBin(std::string str){
    for(int i=0;i<str.size();i++){
        int number=stoi(str[i]);
        std::cout<<number<<std::endl;
    }
    return "a";
}
int main()
{
fakeBin("12354234");
return 0;
}

编译时

int number=stoi(str[I]);

我收到此错误:

“stoi”未在此范围内声明

您能解释一下为什么我会收到此错误吗?

c++ string integer c++17
3个回答
1
投票

std::stoi
函数以
std::string
为参数。我想问题是为什么下面的代码有效,但你的代码无效。

std::string s = "1";
int i = stoi(s);

由于

依赖于参数的查找(ADL)
,上面的代码在没有 std:: 前缀的情况下也可以正常编译。 基本上,如果参数位于命名空间中,函数解析也将在该命名空间中执行。 在本例中,
string
位于
std
命名空间中。

但是,在您的情况下,提供的参数是

char
参考。 由于名称空间中没有参数,因此函数解析仅发生在全局范围内,因此会失败。

当显式提供

std::stoi
时,函数解析成功。 在这种情况下,
std::string
是从
char
引用隐式构造的,并作为第一个参数给出给
stoi

请注意,能够在 ADL 的帮助下避免键入函数的名称空间并不一定意味着您应该这样做。 显式键入名称空间可以防止此类问题。 如果不出意外的话,它会告诉未来的读者一个函数的起源。


0
投票

你应该写 std:: stoi 或者您可以在头文件后面添加一行“using namespace std;”。

还有另一个错误:stoi 只适用于字符串。这里 str[i] 是一个字符。所以你必须创建一个空字符串变量 string s=""; 然后 s= s+ str[i] ;之后你可以做 std:: stoi(s);


0
投票

std::
之前使用
stoi
(
std::stoi
)

std::stoi
参数不正确,因此您没有使用正确的语法,请尝试按如下方式修复它:

int       stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 );
int       stoi( const std::wstring& str, std::size_t* pos = nullptr, int base = 10 );

并且至少使用

c++11

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.