首页 > 解决方案 > 我的代码将打印两次错误消息并仍然运行

问题描述

我遇到了一个问题,我的代码应该查找重复值并在 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;
}

标签: cfunctionif-statementbooleansubstitution

解决方案


嗨,我猜你的意思是当你谈论抛出错误时返回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");
}

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

笔记:

这种嵌套的 for 循环对于较大的字符串效率低下。


推荐阅读