我的代码将打印两次错误消息,并且仍然可以运行 示例解决方案

问题描述

我遇到一个问题,我的代码应查找重复值,如果为true,则抛出错误,否则将bool值设置为“ true”。但是由于某种原因,它会两次打印错误消息,并且仍在执行其余代码。我什至尝试了另一种选择,但都给出了相同的结果(if语句已注释掉)请在这里帮助我:

bool key_check(string argv[])
{

int string_c = strlen(argv[1]);
bool key_c;
int dup[string_c];

if (string_c == 26)
{

    for (int i = 0; i < string_c; i++)
    {
        if(isalpha(argv[1][i]))
        {
                if(strcmp(argv[1],argv[1]) != 0)
                {
                    key_c= true;
                }
                else
                {   //this line is being printed twice and instead of terminating code it allows it to run
                    printf("Key must not contain duplicates.\n");
                    return 1;
                  
                }

                /*if(dup[argv[1][i] - 65] == false && dup[argv[1][i] - 97] == false )
                {
                    key_c= true;
                }
                else
                {
                  printf("Key must not contain duplicates. %c \n",argv[1][i]);
                  key_c = false;
                  return 1;
                }*/
            //}
        }
        else
        {
            printf("Key must only contain characters. \n");
            key_c= false;
            return 1;

        }
    }
}
else
{
   printf("Key must contain 26 characters. \n");
    key_c= false;
}

return key_c;
}

解决方法

嘿,我想你的意思是当谈论抛出错误时返回 false

在C语言中,除0以外的所有值都等于true,所以如果您说:

return 1; // true

在您的函数上下文中,然后宣布调用函数成功。

因此这没有什么意义:

 printf("Key must only contain characters. \n");
 key_c= false;
 return 1;

在这里,您将 key_c 设置为false,然后返回true。

示例解决方案

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

#define TRUE 1
#define FALSE 0

int
key_check(char *argv)
{
    const int EXPECTED_LEN = 26;
    char buffer[26] = {0};
    
    if(strlen(argv) != EXPECTED_LEN) {
        printf("Key must contain 26 characters. \n");
        return FALSE;
    }

    for(int i = 0; i < EXPECTED_LEN; i++) { 
        for(int j = 0; j < i; j++) {
            if(argv[i] == buffer[j]) {
                printf("Key must not contain duplicates.\n");
                return FALSE;
            }
        }

        buffer[i] = argv[i];
    }
    

    return TRUE;
}

int main() {
    char *s1 = "abcdefghijklmnopqrstuvwxyz"; 
    char *s2 = "abcdefghijklmnopqistuvwxyz"; 
    char *s3 = "abcdefghijklmnopqistuvwxy";

    printf("%s has only unique characters.. %s\n",s1,key_check(s1) ? "Yes" : "Nope");
    printf("%s has only unique characters.. %s\n",s2,key_check(s2) ? "Yes" : "Nope");
    printf("%s has the right length.. %s\n",s3,key_check(s3) ? "Yes" : "Nope");
}

我使用像您一样的char缓冲区来存储所有已经出现的字母。然后,我检查字符串长度是否与键的预期长度匹配,否则返回false。否则,函数将继续并遍历输入字符串。我使用嵌套的for循环来检查字符是否已经出现,如果没有,请继续搜索,将当前字符添加到缓冲区中。如果字符串仅包含唯一字母,则我们到达函数的结尾并返回1表示成功。

注意:

此嵌套的for循环对于较大的字符串无效。