c - 难以理解 C 中的函数
问题描述
我正在完成一项编程任务。我在 main 中进行了密钥验证,但决定尝试使其成为一个单独的函数。我还不太了解函数,所以我看不出哪里出错了。每当我运行程序时,即使我知道它不是,我总是只会得到“密钥有效”。正如我所说,该程序在 main 中运行良好。
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int validate (int c, string v[]); //prototpe validate function
int main (int argc, string argv[])
{
int validate (int argc, string argv[]); //run validate for argc and argv
printf("Key is valid\n"); //if valid, print message
}
int validate (int c, string v[])
{
//Validate that only one Command Line Argument was entered
if (c != 2) //Check the number if entered commands at execution
{
//If more than one, print error message
printf("Key must be the only Command Line Argument\n");
return 1; //Return false
}
//Validate that Key length is 26 characters
if (strlen(v[1]) != 26) //Don't forget null 0
{
printf("Key must contain exactly 26 characters\n");
return 1; //Return false
}
//Validate that all Key characters are alphabetic
for (int i = 0, n = strlen(v[1]); i < n; i++)
{
//Check each element of the array
if (isalpha(v[1][i]))
{
continue; //Continue if alphabetic
}
else
{
//if non-alphabetic, print error code
printf("Key must contain only alphabetic characters\n");
return 1; //Return false
}
}
//Validate that each Key character is unique
for (int x = 0, z = strlen(v[1]) - 1; x < z; x++)
{
//Create a second loop to compare every element to the first before incrementing the first
for (int y = x + 1; y < z; y++)
{
//Cast array elements to int, check if each element equals next element in array
if (v[1][x] == v[1][y])
{
printf("Key must contain exactly 26 unique characters\n");
return 1;
}
}
}
return 0; //Key is valid, so return true
}
解决方案
您只是在声明该函数,而不是运行该函数并无条件地validate
打印。Key is valid
要运行该函数并仅在它返回时validate
打印,该函数应如下所示:Key is valid
0
main
int main (int argc, string argv[])
{
if (validate (argc, argv) == 0) //run validate for argc and argv and check its response
{
// put printing inside if statement so that it runs only if the condition is true
printf("Key is valid\n"); //if valid, print message
}
}
推荐阅读
- xamarin - Calling method from ViewModel cause System.NullReferenceException
- javascript - 在使用 cloud firestore .get() doc.exists 时,即使文档存在,它也始终保持未定义
- python - 重新分区 pyspark 数据帧后无法执行连接
- arrays - 如何使用 jq 获取 {"k":foo, "v":bar} 项的 JSON 列表中的键值?
- reactjs - UseEffect 改变不是立竿见影的吗?但它仍然以某种方式呈现
- html - 以角度创建反应形式时出错
- flutter - 如何在颤动的列内使用 StaggeredGridView?
- c# - 计算临床仪器的校验和
- python - TypeError:列表索引必须是整数,而不是列表问题中的str
- javascript - 作为前端 javascript 开发人员的登录身份验证问题,,,