【发布时间】:2012-09-22 13:55:26
【问题描述】:
我遇到了一个小型 C 程序的问题。它输出一个问题(见下面的代码),我可以将其输入(y 和 n),但随后什么也没有发生,即使它是为了根据输入的输入(y 或 n)打印一些东西。但是,在我的问题之后没有输出任何内容,程序就退出了。代码如下:
#include <stdio.h>
int main()
{
char string [80];
static char y;
static char n;
printf( "ARE YOU SHAQIRI? [y/n]: " );
scanf( "%s", string );
if ("%s" == "y")
printf("That's impossible. YOU CANNOT BE SHAQIRI YOU IDIOT");
else if ("%s" == "n")
printf("I thought not.");
fflush ( stdin );
return 0;
}
【问题讨论】:
-
当 y/n 响应只需要一个字符时,为什么要浪费 80 字节的字符串呢?只需
getchar()而不是scanf() -
永远不要在
stdin上调用fflush- 这会导致未定义的行为。另外,你为什么要让你的局部变量static? -
这是根本错误:"%s" 并不神奇。它只是带有百分号和 s 的文字字符串。所以 "%s" == "y" 将永远为假,"%s" == "n" 也是如此。
标签: c string conditional stdin