如果一个字符,比如说"9",我减去"0",我在结果上使用 is 数字,我是真还是假



如果一个字符,假设'9',我减去'0',我在结果上使用数字,我是真还是假

我正在使用leetcode来尝试atoi,关于函数isdigit的基本概念问题卡住了我。

if(isdigit(str[i]-'0')==false){
return str[i]-'0';
break;
}

输入: "42" 输出: 4 预期: 42

我想知道如果 str[i] 等于字符'0' isdigit 函数是否会返回 true。

Noisdigit对字符而不是整数进行操作,因此正确的代码是

isdigit(str[i]) == false

你混淆了两个不同的东西,isdigit(str[i])测试str[i]是否是一个数字(即'0''1''2'等(,str[i] - '0'将数字转换为数值。

isdigit采用 int,即字符代码,并将其与数字字符的字符代码进行比较。在 ASCII 中:

'0' - 48
'1' - 49
'2' - 50
'3' - 51
'4' - 52
'5' - 53
'6' - 54
'7' - 55
'8' - 56
'9' - 57

因此,如果您以"4"-"0"为例,则最终得到 52 - 48 = 4。 4 是 EOT 的字符代码,不是数字。您可以看到,如果您的字符串由数字组成,它将永远不会返回 true。如果您在字符串中使用其他字符,它可以返回 true,例如:

#include <iostream>
#include <string>
#include <cctype>
int main() 
{
std::string str = "g";
if (std::isdigit(str[0]-'0'))
std::cout << "Success: " << int(str[0]-'0');
else
std::cout << "No cigar";
return 0;
}

结果为 55,因为"g"是 103,"0"是 48。 103 - 48 = 55 和 55 是"7"的字符代码

相关内容

最新更新