简体   繁体   English

读取字符时c中的scanf错误

[英]scanf error in c while reading a character

#include <stdio.h>

int main()
{
    char TurHare; 

    while(1)
    {
        scanf("%c",TurHare);
     printf("\nCharacter :%c", TurHare);
 }
    return 0;
}

When I compile and then run the program the output is like : 当我编译然后运行程序时,输出如下:

w
Character : w
Character : 

where w is the input from console. 其中w是来自控制台的输入。

It should appear like: 它应该看起来像:

w
Character : w

How to do it? 怎么做?

You missed &. 你错过了 &。

retry with 重试

int main()
 {
char TurHare;   

    while(1)
    {
    scanf("%c",&TurHare);
    printf("\nCharacter :%c", TurHare);
    }

return 0;
} 

I recommend getch,getche,getchar to use in case of character ,scanf will lead you to some buffering problem 我建议使用getch,getche,getchar来处理字符,scanf会导致您遇到一些缓冲问题

Ok so Its because of return key which you enter after entering w. 好的,这是因为您在输入w之后输入了回车键。 so once it reads w and other time it read the end of line character. 因此,一旦读取w而其他时候读取行尾字符。

There is an buffering-problem with scanf("%c"). scanf(“%c”)有一个缓冲问题。 Many people use fflush(stdin) to solve, but isnt ANSI. 许多人使用fflush(stdin)来解决问题,但不是ANSI。

void fflushstdin()
{
    int c;
    while( (c=getchar())=='\n' );
    if( c!=EOF )
        ungetc(c,stdin);
}

main()
{
    int TurHare;
    while( fflushstdin(), !feof(stdin)&&1==scanf("%c",&TurHare) )
    {
        printf("\nCharacter :%c", TurHare);
    }
    return 0;
}

Break the loop with ^Z on Windows and ^D with Unix/Linux. 在Windows上用^ Z打破循环,在Unix / Linux上用^ D打破循环。

Your program does what you tell it to do, it outputs the characters you type. 程序会执行您要执行的操作,并输出您键入的字符。

Now when you input w , look at what you're doing. 现在,当您输入w ,请看您在做什么。 You're hitting 2 keys. 您正在敲2个键。 the w key , and Enter . w键,然后Enter That's the output you get, w and a newline(from the enter key). 那就是您得到的输出w和换行符(从enter键)。 If you don't want that, do eg 如果您不想这样做,请例如

char TurHare; 

while(1)
{
    if(scanf("%c",&TurHare) != 1) { //always check for errors
       break; //or some other error handling
    }

    if(c != '\n') { //or perhaps if(!isspace(c)) from <ctype.h>
      printf("\nCharacter :%c", TurHare);
      fflush(stdout);
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM