首页 > 解决方案 > 即使我输入了一个数字,为​​什么我的代码仍然返回 1 和错误消息?

问题描述

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

该程序应该可以工作,用户键入 ./Caesar 后跟一个空格和一个整数。它应该打印成功和给定的整数。如果用户要键入除此之外的任何其他内容,即。2x 或任何字符等,它应该打印 Usage: ./caesar key。

// 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; 
    }


}

标签: ccs50

解决方案


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))

推荐阅读