为什么我的代码一直返回 1 和错误消息,即使我输入了一个数字?

Why does my code keep returning 1 with the error message even though I input a digit?

我正在尝试完成 pset 2 上的 Caesar 练习。我的代码编译正常,但它似乎给了我输出 Usage: ./caesar key 即使我输入了一个 int。非常感谢您对我出错的地方提供帮助:)

该程序应该可以让用户键入 ./Caesar,然后输入 space 和一个整数。它应该打印成功和给定的整数。如果用户要键入除此以外的任何其他内容,即。 2x 或任何字符等,它应该打印 用法:./凯撒钥匙.

// Libraries
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, string argv[])

{

    if (argc == 2 && (atoi(argv[1]) > 0))
     for(int i = 0, len = strlen(argv[1]); i < len; i++)
        {
           char n = argv[1][i];
           int digit = isdigit(n);


           if (n != digit)
            {
                printf("Usage: ./caesar key\n");
                return 1;
            }

          else
            {
                printf("Success\n %i", digit);
                return 0;
            }  


        }

    else 
    {
       printf("Usage: ./caesar key\n");
       return 1; 
    }


}

你的代码 returns 每次因为语句

1

if(n != digit)

isdigit() C 中的函数 returns 如果传递给它的字符是数字,即 0 到 9 之间的非零值 (1)。 当你比较ndigit时,就会比较n和digit的ascii值。因此,如果条件将始终导致 True,因为 ndigit 将不相等。

我猜你想要比较的是数字是否为零,即

if(digit == 0)

int digit = isdigit(n);
if (n != digit)

应该是

int digit = isdigit(n);  // 0 (false) if n isn't a digit; non-zero (true) if n is a digit.
if (!digit)

或者只是

if (!isdigit(n))