我找不到cs50的替换代码有什么问题?(用于检查关键部件)[关闭]

dgjrabp2  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(43)

**已关闭。**此问题需要debugging details。它目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答这个问题。
9天前关闭。
Improve this question
我正在尝试解决the substitution problem on CS50 course。在我完成它之后,我试图编译,但它不能正常工作。它总是返回./sustitiuion键部分,即使我给予true键。你能看出哪里不对吗?
当我检查钥匙的部分似乎不正确,我几乎肯定不应该有问题,因为我在互联网上检查了相同的部分,它几乎是相同的。

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./substituion key \n");
        return 1;
    }
    //validate the key!

    string key = argv[1];

    for (int i = 0; i < strlen(key); i++)
    {
        if (!isalpha(key[i]))
        {
            printf("Usage: ./substitution key\n");
        }
    }

    for (int j = 0; j < strlen(key); j++)
    {
        for (int k = 0; k < strlen(key); k++)
        {
            if (toupper(key[j]) == toupper(key[k]))
            {
                printf("Usage: ./substitution key \n");
                return 1;
            }
        }
    }

    if (strlen(argv[1]) != 26)
    {
        printf("Usage: ./substituion key \n");
        return 1;
    }

字符串
为什么这门课的问题这么难?

kt06eoxx

kt06eoxx1#

问题出在测试重复字母的代码中:如果索引jk不同,则只应检查字母是否不同。@chux建议的一种有效方法是从j + 1迭代k到字符串的长度。
下面是一个修改过的循环:

for (int j = 0; j < strlen(key); j++)
    {
        for (int k = j + 1; k < strlen(key); k++)
        {
            if (toupper(key[j]) == toupper(key[k]))
            {
                printf("Usage: ./substitution key \n");
                return 1;
            }
        }
    }

字符串
更一般地说,您应该计算一次字符串长度并将其存储到变量中,以避免在每次循环迭代时重复计算。编译器也许能够优化这些对strlen函数的调用,但在C中使用j < strlen(key)作为循环测试是不好的。
以下是修改后的版本:

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(int argc, string argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: ./substitution key\n");
        return 1;
    }
    //validate the key!

    string key = argv[1];
    int len = strlen(key);

    if (len != 26) {
        fprintf(stderr, "substitution: key must be 26 letters exactly\n");
        return 1;
    }
    for (int i = 0; i < len; i++) {
        if (!isalpha((unsigned char)key[i])) {
            fprintf(stderr, "substitution: key must be letters only\n");
            return 1;
        }
    }

    for (int j = 0; j < len; j++) {
        for (int k = j + 1; k < len; k++) {
            if (toupper((unsigned char)key[j]) == toupper((unsigned char)key[k])) {
                fprintf(stderr, "substitution: duplicate letter '%c'\n", key[j]);
                return 1;
            }
        }
    }

相关问题