gpt4 book ai didi

c++ - 如何在 C++ 中正确地将 char 转换为 int?

转载 作者:行者123 更新时间:2023-11-30 01:11:00 27 4
gpt4 key购买 nike

在 C++ 中将 char 转换为 int 时,我遇到了一个以前从未遇到过的独特问题。

我正在遍历一个名为 total_line 的整数字符串,其内容如下:

1526

我正在尝试将所有其他 char 转换为 int,这是我的代码:

cout << total_line[i+1] <<endl;
int d = total_line[i+1] <<endl;
cout << d << endl;
i++;

奇怪的是我的输出是这样的:

5
53
6
54

我不确定为什么 5 被转换为 int 53 而 6 被转换为 int 54。

最佳答案

正如其他人所提到的,字符实际上表示为映射到字符表的数字。数字到字符的映射因所选字符集而异,例如,对于 US-ASCII,字符 '1''2'对应于数字 49 和 50 ( see here for the full US-ASCII table )。

要将数字的字符串表示形式转换为带符号的整数,请使用 std::stoi (C++11 起)。

以下代码片段会将字符串分割成单独的数字,并分别使用 std::stoi 将它们转换为数字。

for (std::string::size_type i = 0, n = total_line.size(); i != n; ++i) {
int d = std::stoi(total_line.substr(i, 1));

std::cout << d << std::endl;
}

使用标准库函数 std::stoi 的优点是无论字符编码如何都能正常工作。

关于c++ - 如何在 C++ 中正确地将 char 转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36634600/

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