当我在下面的代码中传递一个 string
变量时,g++ 给出一个错误:
无法将参数 ‘1’ 的 ‘std::__cxx11::string {aka std::__cxx11::basic_string}’ 转换为 ‘const char*’ 到 ‘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;
}
但是,如果我将代码更改为:
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
char a[3] = "10";
int b = atoi(a);
cout<<b<<"\n";
return 0;
}
它工作得很好。
请解释为什么 string
不起作用。 string a
和 char a[]
之间有什么区别吗?
原文由 shubz 发布,翻译遵循 CC BY-SA 4.0 许可协议
它们之间是有区别的。每一种都有不同的功能:
细绳
如前所述,对于
string
有stoi
函数:字符*
过去
atoi
用来处理char*
转换。但是,现在
atoi
被替换为strtol
得到 3 个参数:char*
要解析为的字符long
,char**
返回指向解析字符串后的指针,int
对于基数,应从(2、10、16 或其他)解析数字。There are whole bunch of functions like
strtol
likestrtof
,strtod
, orstrtoll
which converts tofloat
,double
,long
和long long
。这些新功能的主要优点主要是错误处理和多基支持。
主要缺点是没有转换为
int
的函数,只有long
(除了其他类型)。有关更多详细信息,请参阅 https://stackoverflow.com/a/22866001/12893141