我刚刚开始自学C,并想用main((编写一个基本程序,该程序将接受用户输入的密码,使用正确的密码进行检查,并具有适当的输出。但是,程序开始运行并读取用户输入,但随后突然终止,出现错误分段错误(代码转储(。导致错误的代码有什么问题?
#include <stdio.h>
int main(void)
{
printf("Enter the passwordn");
char guess;
scanf(" %c", &guess);
char password[] = "Hello123";
int correct = 0;
while (correct != 1){
if(strncmp(password,guess)==0){
printf("Success! You have logged in with your password
%cn",guess);
correct +=1;
}
else
{
printf("Incorrect password. Try againn");
}
}
}
嘿,
我有幸重新编码了你的代码
#include <stdio.h>
#include <string.h>
int main(void)
{
char *guess;
const char password[] = "Hello123";
int correct = 0;
while (correct != 1){
/*
* Include the input prompt inside while loop
*/
if (correct == 0){
printf("Enter the passwordn");
scanf(" %s", guess);
}
if(strncmp(password,guess, 10)==0){ //strncmp accept 3 params, set length e.g 10
printf("Success! You have logged in with your password %sn",guess);
correct = 1;
}
else
{
printf("Incorrect password. Try againn");
correct = 0;
}
}
}