scanf(“%c”) automatically reads 10

隐身守侯 提交于 2021-02-16 21:13:10

问题


void main() 
{ 
    int cnt=1; 
    char i; 
    while(cnt<4) 
    {
        printf("\nenter the character"); 
        scanf("%c",&i); 
        if(i>64 && i<91) 
            printf("\ncharacter is entered"); 
        else 
            printf("\nnumber is entered"); 
        cnt++; 
    }
}

In the above program, during the second iteration, i automatically takes 10. So the control goes to else part. Can anyone help me find what is the issue?


回答1:


In the first iteration, you type a character and press Enter. scanf consumes the character you entered, leaving the \n in the standard input stream (stdin).

In the second iteration, scanf sees the \n character consumes it, thus not waiting for further input.

You can tell scanf to read and discard the next character by using:

scanf("%c%*c", &i);

or you can tell scanf to read and discard all whitespace characters, if any, before reading a character and storing it in i by using:

scanf(" %c",&i);
/*     ↑ Note the space */


来源:https://stackoverflow.com/questions/35110942/scanfc-automatically-reads-10

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!