【问题标题】:Problems with atoi() exerciseatoi() 练习的问题
【发布时间】:2014-08-03 07:14:09
【问题描述】:

我在这个简单的循环练习中遇到了问题。我认为代码是正确的,我没有收到任何错误,但是当我运行程序时,我只是一遍又一遍地得到“^C”。请帮忙。

#import <readline/readline.h>
#import <stdio.h>
#include <stdlib.h>

int main(int argc, const char * argv[])
{
    printf("Where should I start counting? ");
    const char *numInput = readline(NULL);
    int countDownStart = atoi(numInput);
    for (int i = countDownStart; i >= 0; i--) {
        if (i % 3 == 0){
            printf("%d\n", i);
            if (i % 5 == 0) {
                printf("Found one!\n");
            }
        }
    }

    return 0;

}

2014 年 8 月 3 日更新

当我使用键盘上方的数字输入起始数字时,该代码有效。但是,当我用 10 键输入起始数字时,每次按 Enter 键都会得到“^C”。现在我完全糊涂了,但至少我的代码有效。

感谢大家的帮助。我知道 atoi 不是最好的函数,但我正在尝试阅读 Big Nerd Objective-C 书。

【问题讨论】:

  • 你的程序能编译吗? #import 指令通常用于 MS 上的库。它们应该是#include。

标签: c loops atoi


【解决方案1】:

使用 strtol 代替 atoi,因为它在转换失败的情况下返回错误值。

【讨论】:

  • 感谢您的帮助。
【解决方案2】:

你必须检查从函数 readline 收到的输出

const char *numInput = readline(NULL);
printf ("Input %s", numInput); //debugging
int countDownStart = atoi(numInput);

如果函数总是返回相同的字符串意味着,那么结果也将保持不变。

【讨论】:

  • 感谢您的帮助。我会继续这样做。