.cpp:23:错误:无法将'std :: string'转换为'const char*'以将参数'1'转换为'int atoi(con​​st char*)'

1 c++ string

这里有一个我试图运行的基本代码但是我遇到stoi问题(这是c ++)我一直收到错误:

‘stoi’ was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

我试过atoi和strtol这个错误

.cpp:23: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’
Run Code Online (Sandbox Code Playgroud)

代码:

using namespace std;

int main(){
    string numberGuessed;
    int intNumberGuessed = 0;
    do {
        cout << "Guess a numeber btw 1 - 10: " << endl;
        getline(cin, numberGuessed);
        intNumberGuessed = atoi(numberGuessed);
        cout << intNumberGuessed << endl;
    } while(intNumberGuessed != 4);
    cout<< "you win" << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Hi-*_*gel 7

atoi()函数接受const char*参数,但您尝试传递它std::string.写它就像intNumberGuessed = atoi(numberGuessed.c_str());拿指针.

至于第一个错误,关于stoi()未声明 - 这是因为该函数是在C++ 11标准中添加的,因此您必须在编译器中启用它的支持.即在较旧版本的GCC中你可以使用-std=c++11选项(因为默认情况下启用gcc5 C11,因为默认情况下将启用 gcc6 C++ 11).