无法将字符/字符串转换为整数

11

当我运行我的代码时,编译时出现了这个错误:

# 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;
}

1
无法使用单个char参数创建std::string - chris
int num = std::stoi (&one.c_str ()[2]); 可以工作,但这仅因为它是 C 字符串中最后一个非 NULL 字符。 - Andon M. Coleman
1个回答

18

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]));

1
我总是会忘记这样的事情。我已经使用弱类型语言有一段时间了。谢谢! - Jossie B

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接