C++ 无法将字符/字符串转换为int

C++ 无法将字符/字符串转换为int,c++,C++,当我运行代码时,在编译时会出现以下错误: # g++ -std=c++0x sixteen.cpp -O3 -Wall -g3 -o sixteen sixteen.cpp: In function ‘int main()’: sixteen.cpp:10: error: call of overloaded ‘stoi(char&)’ is ambiguous /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/

当我运行代码时,在编译时会出现以下错误:

# g++ -std=c++0x sixteen.cpp -O3 -Wall -g3 -o sixteen
sixteen.cpp: In function ‘int main()’:
sixteen.cpp:10: error: call of overloaded ‘stoi(char&)’ is ambiguous
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/basic_string.h:2565: note: candidates are: int std::stoi(const std::string&, size_t*, int) <near match>
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/basic_string.h:2626: note:                 int std::stoi(const std::wstring&, size_t*, int) <near match>

std::stoi
std::string
作为其参数,但
one[2]
char

解决此问题的最简单方法是使用数字字符保证具有连续值的事实,因此您可以执行以下操作:

int num = one[2] - '0';
或者,您可以将数字提取为子字符串:

int num = std::stoi(one.substr(2,1));
另一种选择是,您可以使用构造函数构造
std::string
,该构造函数接受
char
以及
char
应该出现的次数:

int num = std::stoi(std::string(1, one[2]));

std::string
不能从单个
char
参数生成。
int num=std::stoi(&one.c_str()[2])
可以工作,但这只是因为它是C字符串中最后一个非空字符。我总是忘记类似的事情。我使用弱类型语言的时间有点太长了。谢谢
int num = std::stoi(std::string(1, one[2]));