【问题标题】:why is my string being read this way?为什么我的字符串被这样读取?
【发布时间】:2017-03-15 04:05:30
【问题描述】:

我正在尝试重新创建 atoi,但我想知道为什么我的函数有效。我最终将三个顶级语句的它更改为 str[i],因为它对我来说很有意义,但它通过了我扔给它的所有内容。

i = 0;
result = 0;
negative = 1;
if (str[0] == '-')
{
    negative = -1;
    i++;
}
if (str[0] == '+')
    i++;
while (str[0] <= ' ')
    i++;
while (str[i] != '\0')
    if (str[i] >= '0' && str[i] <= '9')
    {
        result = result * 10 + str[i] - '0';
        ++i;
    }
return (result * negative);

【问题讨论】:

  • 在最后的 while 循环中,您忽略了任何不是数字的内容。这是你的意思还是应该抛出错误? 12A3 现在将返回 123

标签: string loops if-statement while-loop


【解决方案1】:

第一个 if 语句只是检查数字是否应该为负数。 第二个 if 语句检查字符串是否以可选的正号开头 如果 ascii 的字符小于空格的 ascii,则第一个 while 循环应该运行到无穷大(32) 第二个 while 循环简单地遍历字符串并将字符串转换为 int

将前 3 个 str[0] 更改为 str[i] 应该不会有太大区别,因为 i 已初始化为 0。如果您的字符串以“-+”开头,则不应该是一个例外。有效整数或符号和数字之间有空格

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多