C语言学生信息录入与密码校验程序运行故障问题求解
代码问题汇总
- 字符串比较逻辑完全错误:C语言中不能用
==直接比较两个字符串的内容,该运算符只会对比两个字符串的首内存地址,永远不会相等(除非指向同一块内存);你写的psswrd == "%s%s",yr, stid属于语法逻辑完全错误,逗号表达式最终仅会取最后一个操作数stid的值参与判断,完全达不到拼接后对比的效果。 - 未提前拼接生成正确密码:你没有将
yr(年级班级)和stid(学号)拼接为完整的正确密码字符串,无法直接和用户输入的密码做对比。 - 循环逻辑写反:当前代码判断条件成立时进入循环提示验证失败,你应该是密码不匹配时才进入循环要求重新输入,逻辑完全颠倒。
- printf参数不匹配:输出学生ID的语句
printf("Student ID: %s%s\n",stid );写了2个%s占位符,但只传入了1个参数,会触发未定义行为,输出乱码。 - fgets读取的字符串末尾会残留换行符
\n,输出个人信息时会出现不必要的空行。
正确实现代码
#include <stdio.h> #include <string.h> // 处理fgets残留的换行符 void trim_newline(char *str) { int len = strlen(str); if (len > 0 && str[len-1] == '\n') { str[len-1] = '\0'; } } int main (){ char fname[25]; char lname[10]; char addr[50]; char yr[10]; char cr[50]; char stid[15]; char correct_pwd[25]; // 存储拼接后的正确密码 char psswrd[50]; printf("Welcome to the Code! \n"); printf("Please Input your First Name: "); fgets(fname, 25, stdin); trim_newline(fname); printf("Please Input your Last Name: "); fgets(lname, 10, stdin); trim_newline(lname); printf("Please Input your address: "); fgets(addr, 50, stdin); trim_newline(addr); printf("Please Input your Course: "); fgets(cr, 50, stdin); trim_newline(cr); printf("Please Input your College Year & Section: "); scanf("%s", yr); printf("Please Input your Student ID: "); scanf("%s", stid); // 拼接生成正确密码 strcpy(correct_pwd, yr); strcat(correct_pwd, stid); printf("\nYour Details:\n"); printf("First Name: %s\n", fname); printf("Last Name: %s\n", lname); printf("Address: %s\n", addr); printf("College Year: %s\n", yr); printf("Course: %s\n", cr); printf("Student ID: %s\n", stid); printf("Your Password: %s\n", correct_pwd); printf("Please Input your New Password to Get Verified: "); scanf("%s", psswrd); printf("You Have Inputted: %s\n", psswrd); // 密码不匹配就循环重输 while (strcmp(psswrd, correct_pwd) != 0) { printf("Verification Failed. \n"); printf("Please Input Your Password: "); scanf("%s", psswrd); printf("You Have Inputted: %s\n", psswrd); } printf("Verification Successful! \nThank you for Using the Code!"); return 0; }
内容的提问来源于stack exchange,提问作者Meat_Salad
相关产品推荐
相关产品推荐

