当我运行我的代码时,我在编译时遇到了这个错误:
# 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>
我查找了该错误并按照此处其他问题的说明进行操作,但是在删除 using namespace std;
后我仍然遇到该错误。为什么这种情况仍然发生,我该怎么做才能摆脱它?
代码:
#include <iostream>
#include <string>
int main() {
std::string test = "Hello, world!";
std::string one = "123";
std::cout << "The 3rd index of the string is: " << test[3] << std::endl;
int num = std::stoi(one[2]);
printf( "The 3rd number is: %d\n", num );
return 0;
}
最佳答案
std::stoi
接受一个 std::string
作为它的参数,但是 one[2]
是一个 char
.
解决此问题的最简单方法是利用数字字符保证具有连续值这一事实,因此您可以这样做:
int num = one[2] - '0';
或者,您可以将数字提取为子字符串:
int num = std::stoi(one.substr(2,1));
还有另一种选择,您可以使用采用 char
的构造函数和 char
的次数来构造 std::string
应该出现:
int num = std::stoi(std::string(1, one[2]));
关于c++ - 无法将字符/字符串转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21270162/