首页 > 解决方案 > 只有 main() 函数在 C 中执行

问题描述

开始学习 C。main函数执行得很好,但是程序在没有执行第二个函数的情况下完成运行。我觉得我在 main 的 for 循环中犯了一个错误。

int check_key_length(int count);

int main(void)
{
    char key[20];
    int count = 0; 

    printf("Enter key: ");
    scanf("%s", key);
 
    for(int i = 0; i < strlen(key); i++) 
    {  
        if (key[i] != ' ')
            count++;  
    }  

    printf("Total number of characters in a string: %d", count); 

}


int check_key_length(int count)
{
    int set_amount = 26;

    if (count < set_amount)
        printf("Error: Your key is too short! Please input 26 chars\n");
    else if (count > set_amount)
        printf("Error: Your key is too long! Please input 26 chars\n");
    else
        string message = get_string("Enter string to encrypt: ");

    return 0;
}

标签: cfunction

解决方案


您转发声明了您的函数,为其提供了定义,但是您需要在 main 中调用该函数以使您的机器执行它,这样的事情会按预期调用您的函数

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

int check_key_length(int count);

int main(void)
{
    char key[27];
    int count = 0;
    int strLength;

    do {
        printf("Enter key: ");
        scanf("%s", key);

        strLength = strlen(key);
    } while(check_key_length(strLength) != 0);
    
    
    for(int i = 0; i < strLength; i++) 
    {
        if (key[i] != ' ')
        {
            count++;  
        }
    }

    printf("Total number of characters in a string: %d\n", count);

    return 0;
}

int check_key_length(int count)
{
    int set_amount = 26;

    if (count < set_amount)
    {
        printf("Error: Your key is too short! Please input 26 chars\n");
        return -1;
    }
    else if (count > set_amount)
    {
        printf("Error: Your key is too long! Please input 26 chars\n");
        return -2;
    }
    else
    {
        return 0;
    }
}

请注意,我必须稍微修改代码才能在没有任何警告或错误的情况下构建它,我可能以一种你不期望的方式改变了行为,所以在粘贴之前检查我的代码


推荐阅读