用C scanf函数的问题(QUOT;%C")函数读取字符一个接一个 [英] Problems with C scanf("%c") function to read characters one by one

查看:88
本文介绍了用C scanf函数的问题(QUOT;%C")函数读取字符一个接一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code产生一个​​非常奇怪的结果,当我运行它。

The following code produces a very strange result when I run it.

#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;
         }
     }
}

我希望发生的是对于每当我输入W继续循环,所以我可以输入W一次。它所做的虽然是去else语句,即使我输入W。这似乎只是跳过 scanf()的行。我也问过我认识的人谁知道C,但他们不知道如何解决它。

What I want to happen is for the whenever I input 'w' it continues the loop so I can input 'w' again. What it does though is go to the else statement even though I input 'w'. It just seems to skip the scanf() line. I have asked everyone I know who knows C but they do not know how to solve it.

有人请帮我在这里!

推荐答案

这是因为你键入<大骨节病>是W 后跟<大骨节病> ENTER 。因此,有在输入2个字符,'W',后跟一个换行符( \\ n )。后者会导致采取第二迭代其他分支。

This is because you type w followed by ENTER. So there are 2 characters in the input, 'w', followed by a newline (\n). The latter causes the else branch to be taken on the second iteration.

请注意,当连接到终端标准输入是行缓冲。如果你需要立即处理的人物,有办法做到这一点。请参阅 comp.lang.c常见问题的详细信息(我怎样才能读取单个字符从键盘,而无需等待回车键?我怎样才能阻止字符在屏幕上被回送为他们输入?)。

Note that standard input is line buffered when connected to a terminal. If you need to deal with characters immediately, there are ways to do that. See the comp.lang.c FAQ for details ("How can I read a single character from the keyboard without waiting for the RETURN key? How can I stop characters from being echoed on the screen as they're typed?").

请注意,对于强大的编程这是一个必须检查 scanf函数的返回值。它返回成功转换的项数。如图所示,你的code不能正确处理结束文件的情况下,即当用户键入按Ctrl-D (假设UNIX终端)。然后scanf函数返回 EOF 后没有进行转换,但是你用测试,如果它包含一个有意义的值。

Note that for robust programming it is a must to check the return value of scanf. It returns the number of successfully converted items. As shown, your code does not handle the case of end-of-file properly, i.e. when the user types Ctrl-D (assuming Unix terminal). Then scanf returns EOF and no conversion was performed, but you use test as if it contained a meaningful value.

这篇关于用C scanf函数的问题(QUOT;%C&QUOT;)函数读取字符一个接一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆