c - 只有 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;
}
解决方案
您转发声明了您的函数,为其提供了定义,但是您需要在 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;
}
}
请注意,我必须稍微修改代码才能在没有任何警告或错误的情况下构建它,我可能以一种你不期望的方式改变了行为,所以在粘贴之前检查我的代码
推荐阅读
- android - Kotlin 套接字属性获取器我应该检查异常吗?
- process - 从 Elm 进程接收消息
- python - 使用 python 3.9 创建的 pyenv 虚拟环境使用 python 3.8 setuptools 和 pip 在 pkg_resources 中给出了语法错误
- python - 将 .py 脚本中的变量调用到批处理中
- amazon-web-services - 无法通过 VPCE Endpoint 将私有子网中的 Lambda 连接到 S3
- django - 带有额外配置的 Django DRF 测试 API
- android - 什么可能导致 SharedPreferences 不更新?
- firebase - 如何订购具有 2 个字段的 Cloud Firestore 快照?
- css - NextJS - 无法在 Tailwind CSS 中使用自定义颜色
- javascript - 反应弹簧视差