當我執行并輸入回應“YES”或“NO.”時,程式總是"Not a valid response."
從 else{} 陳述句輸出。
#include<stdio.h>
#include<stdlib.h>
int main()
{
int response[3];
char password[15];
printf("Insert Password with 8 characters:");
gets(password);
printf("Your current password is:'%s',do you want to keep it?(YES or NO.):",password);
gets(response);
if (response == "YES") {
printf("password stored 'not actually lol'\n");
}
else if (response == "NO.") {
printf("we dont know what else you want to do.\n");
}
else {
printf("Not a valid response.\n");
}
return 0;
}
當程式不接受用戶輸入時,它甚至不起作用,我認為 if 陳述句有問題,但我不確定
#include<stdio.h>
#include<stdlib.h>
int main()
{
int response = "NO.";
char password[15];
printf("Insert Password with 8 characters:");
gets(password);
printf("Your current password is:'%s',do you want to keep it?(YES or NO.)\n",password);
//gets(response);
if (response == "YES") {
printf("password stored 'not actually lol'\n");
}
else if (response == "NO.") {
printf("we dont know what else you want to do.\n");
}
else {
printf("Not a valid response.\n");
}
return 0;
}
uj5u.com熱心網友回復:
#include<stdio.h>
#include<stdlib.h>
int main()
{
// You used response[3] sized response which stores 2 characters the user gives, and one character as NULL, hence, it is always suggested to used required size 1 for characters
// Also, "NO." is a char array and not an int array
char response[4];
char password[15];
printf("Insert Password with 8 characters:");
gets(password);
printf("Your current password is:'%s',do you want to keep it?(YES or NO.):",password);
gets(response);
// String comparison is done using strcmp(s1, s2) and not s1 == s2
// If two strings are equal, it returns 0, else 1 or -1
if (strcmp(response, "YES") == 0) {
printf("password stored 'not actually lol'\n");
}
else if (strcmp(response, "NO.") == 0) {
printf("we dont know what else you want to do.\n");
}
else {
printf("Not a valid response.\n");
}
return 0;
}
此外,請閱讀這些網頁以更好地了解為什么不使用gets()
或scanf()
strcmp 用法| 如何在 C 中正確接受輸入
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/524338.html