【问题标题】:How can I exclude non-numeric keys? CS50 Caesar Pset2如何排除非数字键? CS50 凯撒 Pset2
【发布时间】:2020-05-05 22:24:03
【问题描述】:

我正在解决 CS50 Caesar 问题,并且在大多数情况下,我的代码都能正常工作。我无法通过其中一项 check50 测试 - 我的代码不处理非数字键,并且在等待程序退出时超时。

我尝试过使用 isdigit,但它似乎不起作用。

check50 测试结果复制粘贴如下:

:) caesar.c exists.
:) caesar.c compiles.
:) encrypts "a" as "b" using 1 as key
:) encrypts "barfoo" as "yxocll" using 23 as key
:) encrypts "BARFOO" as "EDUIRR" using 3 as key
:) encrypts "BaRFoo" as "FeVJss" using 4 as key
:) encrypts "barfoo" as "onesbb" using 65 as key
:) encrypts "world, say hello!" as "iadxp, emk tqxxa!" using 12 as key
:) handles lack of key
:( handles non-numeric key
    timed out while waiting for program to exit
:) handles too many arguments
#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int main (int argc, string argv[])
{


    if (argc == 2 && (isdigit(argv[1] !=0))
    {


        int k = atoi (argv[1]); // convert string to int
        string s = get_string ("plaintext: "); // obtain text

        printf("ciphertext: ");
        for (int i = 0; i < strlen(s); i++) // text loop
        {
            if (s[i] >= 'a' && s[i] <= 'z')
            {
                printf("%c", 'a' + ((s[i] - 'a') + k) % 26);
            }

            else if (s[i] >= 'A' && s[i] <= 'Z')
            {
                printf("%c", 'A' + ((s[i] - 'A') + k) % 26);
            }

            else
            {
                printf("%c", s[i]);
            }


        }


        printf("\n");
        return 0;
    }



    else
    {
        printf("./caesar key\n");
    }

    return 1;
}

【问题讨论】:

  • “我尝试过使用 isdigit,但它似乎不起作用。”您应该发布代码。
  • 嗨,迈克,感谢您在下面的回答。我对原始帖子进行了编辑以反映我的 isdigit 尝试

标签: c cs50 caesar-cipher


【解决方案1】:

我猜发生超时是因为你的程序正在等待明文,而法官没有给出,因为它除了你的程序在给出非数字键后立即退出。

您可以使用strtol(),它接受指向字符的指针并保存第一个无效字符的位置。

然后,您可以通过检查返回的指针是否指向终止空字符来检查输入是否为数字。

char* p;
int k = (int)strtol (argv[1], &p, 10);
if (*p != '\0') {
    puts("non-numeric key");
    return 1;
}

【讨论】:

    【解决方案2】:

    只需遍历 argv[1] 的每个数字并检查它是否为整数。

    for (int i = 0; i < strlen(argv[1]); i++)
    {
        if (isdigit(argv[1][i]) == 0)
        {
            return 1;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-27
      • 2020-08-02
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      相关资源
      最近更新 更多