当我string在下面的代码中传递一个变量时,g ++给出了一个错误:
不能将'std :: __ cxx11 :: string {aka std :: __ cxx11 :: basic_string}'转换为'const char*'以将参数'1'转换为'int atoi(const char*)'
我的代码是:
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
string a = "10";
int b = atoi(a);
cout<<b<<"\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我将代码更改为:
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
char a[3] = "10";
int b = atoi(a);
cout<<b<<"\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它工作得很好.
请解释为什么string不起作用.有什么区别string a和char a[]?
atoi 是从C传承的旧功能
C没有std::string,它依赖于以null结尾的char数组. std::string有一个c_str()方法,返回一个以null结尾的char*指向字符串数据的指针.
int b = atoi(a.c_str());
Run Code Online (Sandbox Code Playgroud)
在C++ 11中,有一个替代std::stoi()函数,它接受一个std::string参数:
#include <iostream>
#include <string>
int main()
{
std::string a = "10";
int b = std::stoi(a);
std::cout << b << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)