我需要找出程序的正确输入,因此您的程序将输出:“恭喜,今天是您的幸运日!”
#include <stdio.h>
int c = 'n';
int goodPassword() {
// allocate buf and set them all to zero.
char buf[100] = {};
fgets(buf, 100, stdin);
printf(buf);
return c;
}
int main() {
if (goodPassword() == 'y') {
printf("\nCongratulations, it is your lucky day today!\n");
}
else {
printf("\nWrong password, try again.\n");
}
return 0;
}
它将使用什么变量以及为什么也能回答这个问题。
[您应该注意,您在任何地方都没有使用变量c
,并且默认情况下已将其分配为n
,并且在main()
中给出的条件下它保持不变,这就是它抛出Wrong password...
且永不改变的原因。
现在考虑以下内容(如果您只想使用一个字符):
#include <stdio.h>
char c = 'n'; // by default assignment
char goodPassword() // returns CHAR
{
// allocate buf and set them all to zero.
char buf;
buf = getchar();
printf("%c", buf); // print %c, buf not directly buf
return buf; // returns char to function
}
int main()
{
if (goodPassword() == 'y') // user response 'y' success
{
printf("\nCongratulations, it is your lucky day today!\n");
}
else // user response 'n' fails
{
printf("\nWrong password, try again.\n");
}
return 0;
}
注:您不需要使用
c
变量,因为实际上有buf
返回了用户响应的内容。