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

标签 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>

我查找了该错误并按照此处其他问题的说明进行操作,但是在删除 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/

相关文章:

c++ - C++ 的效率

c++ - 与 fgetc() 一起使用的整型变量

C++ 多字符数组比较

c++ - 如何在字符串中获取 0 到 1700 之间的随机数?

c++ - 在循环 C 中使用 libcurl

c++ - 在析构函数中删除 (this) 指针

c++ - 我可以在字符串的 sprintf 中使用 sizeof() 或 #define 来提高精度吗?

c++ - XLL Made by XLW with BOOST UBLAS MyMatrix 数据类型转换为 Double ** 失败

c++ - 搜索功能不起作用

c++ - 如何将 cvCvtColor 转换为 opencv 中的 cvtColor 调用(BGR 到 HSV)?