gpt4 book ai didi

c++ - c++中类型之间的转换

转载 作者:行者123 更新时间:2023-11-27 22:45:44 27 4
gpt4 key购买 nike

我来自其他编程语言,我不明白为什么这段代码会抛出错误。

string n = "123456";
int x;

for(int i = 0; i < n.length(); i++) {

x = atoi( n[i].c_str() );
x *= 2;
cout << x << endl;
}

你能解释一下这起事故吗?并告诉我如何正确地将其转换为整数?

最佳答案

查看return type of std::basic_string::operator[] : 它是 referenceconst_reference。即,对字符 的(const)引用。对于 std::string,这意味着您获得了对 char 的引用,而不是 std::string

C++ 保证数字的字符值是连续且递增的。换句话说,无论字符编码如何,都保证 '1' - '0' == 1'2' - '0' == 2 等等用过的。因此,将包含数字的 char 转换为数字值的方法就是这样做:

x = n[i] - '0';

关于c++ - c++中类型之间的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43294993/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com