当我运行我的代码时,我在编译时遇到此错误:
# 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>
Run Code Online (Sandbox Code Playgroud)
我查看了该错误,并按照此处其他问题的说明进行了操作,但删除后仍然出现错误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;
}
Run Code Online (Sandbox Code Playgroud)
Jos*_*eld 11
std::stoi以a std::string为参数,但是one[2]是char.
解决此问题的最简单方法是使用数字字符保证具有连续值的事实,因此您可以执行以下操作:
int num = one[2] - '0';
Run Code Online (Sandbox Code Playgroud)
或者,您可以将数字提取为子字符串:
int num = std::stoi(one.substr(2,1));
Run Code Online (Sandbox Code Playgroud)
另一种方法是,您可以std::string使用构造函数构造一个,该构造函数占用a char和char应该出现的次数:
int num = std::stoi(std::string(1, one[2]));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5987 次 |
| 最近记录: |