Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C scanf(“%C”函数)逐个读取字符时出现问题_C_Scanf - Fatal编程技术网

C scanf(“%C”函数)逐个读取字符时出现问题

C scanf(“%C”函数)逐个读取字符时出现问题,c,scanf,C,Scanf,下面的代码在运行时产生了一个非常奇怪的结果 #include <stdio.h> #include <stdlib.h> int main(void) { for ( ; ; ) { char test; printf("Please enter 'w' "); scanf("%c", &test); printf("%c\n", test); if (te

下面的代码在运行时产生了一个非常奇怪的结果

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    for ( ; ; )
    {
         char test;
         printf("Please enter 'w' ");
         scanf("%c", &test);
         printf("%c\n", test);
         if (test == 'w')
         {
              printf("Working\n");
         }
         else
         {
              printf("ERROR\n");
              return 0;
         }
     }
}
#包括
#包括
内部主(空)
{
对于(;;)
{
煤焦试验;
printf(“请输入“w”);
scanf(“%c”、&test);
printf(“%c\n”,测试);
如果(测试=='w')
{
printf(“工作”);
}
其他的
{
printf(“错误\n”);
返回0;
}
}
}
我想要发生的是,每当我输入“w”时,它就会继续循环,这样我就可以再次输入“w”。尽管我输入了“w”,但它所做的是转到else语句。它似乎跳过了
scanf()
行。我问过我认识的每个知道C的人,但他们不知道如何解决它

谁来帮帮我

这是因为键入w后跟着ENTER。因此,输入中有两个字符,
'w'
,后跟一个换行符(
\n
)。后者导致在第二次迭代中执行
else
分支

注意,当连接到终端时,标准输入是线路缓冲的。如果您需要立即处理角色,有几种方法可以做到这一点。有关详细信息,请参见(“如何在不等待返回键的情况下从键盘读取单个字符?如何在键入字符时阻止字符在屏幕上回声?”)


请注意,对于健壮的编程,必须检查
scanf
的返回值。它返回成功转换的项目数。如图所示,您的代码无法正确处理文件结尾的情况,即当用户键入Ctrl-D(假定为Unix终端)时。然后scanf返回
EOF
,没有执行任何转换,但是您使用
test
,就好像它包含一个有意义的值一样。

正如Jens所说,您必须使用
'\n'
,在
scanf()
之后使用
getchar()
,您需要执行类似的操作

     scanf("%c", &test);
     while(getchar()!='\n');

将输入带到空格或
\n
(以先到者为准),并将
\n
保留在缓冲区中

,正如Jens所说。您必须忽略换行符
'\n'

scanf(" %c", &test);
在格式说明符
“%c”
的开头添加空格将忽略换行符
“\n”

scanf(" %c", &test);

使用
%c”
也将忽略其他空白,如
\t
空格
\b
\v
\r

这并不能回答问题。要评论或要求作者澄清,请在他们的帖子下方留下评论。正如您所看到的,Jens没有对getchar()说任何话,所以这不是澄清,而是回答