How to convert a single char into an int(如何将单个char转换为int)
问题描述
我有一串数字,例如123456789",我需要提取它们中的每一个以在计算中使用它们.我当然可以通过索引访问每个 char,但是如何将其转换为 int?
I have a string of digits, e.g. "123456789", and I need to extract each one of them to use them in a calculation. I can of course access each char by index, but how do I convert it into an int?
我研究了 atoi(),但它需要一个字符串作为参数.因此,我必须将每个字符转换为字符串,然后在其上调用 atoi.有没有更好的办法?
I've looked into atoi(), but it takes a string as argument. Hence I must convert each char into a string and then call atoi on it. Is there a better way?
推荐答案
你可以利用数字的字符编码都是从 48('0')到 57('9')的顺序.这适用于 ASCII、UTF-x 和几乎所有其他编码(请参阅下面的评论了解更多信息).
You can utilize the fact that the character encodings for digits are all in order from 48 (for '0') to 57 (for '9'). This holds true for ASCII, UTF-x and practically all other encodings (see comments below for more on this).
因此,任何数字的整数值都是数字减去0"(或 48).
Therefore the integer value for any digit is the digit minus '0' (or 48).
char c = '1';
int i = c - '0'; // i is now equal to 1, not '1'
是同义词
char c = '1';
int i = c - 48; // i is now equal to 1, not '1'
但是我发现第一个 c - '0'
更易读.
However I find the first c - '0'
far more readable.
这篇关于如何将单个char转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将单个char转换为int


基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01