Read two characters consecutively using scanf() in C

前提是你 提交于 2019-12-24 02:33:38

问题


I am trying to input two characters from the user t number of times. Here is my code :

int main()
{
    int t;
    scanf("%d",&t);
    char a,b;

    for(i=0; i<t; i++)
    {
        printf("enter a: ");
        scanf("%c",&a);

        printf("enter b:");
        scanf("%c",&b);
    }
    return 0;
}

Strangely the output the very first time is:

enter a: 
enter b:

That is, the code doesn't wait for the value of a.


回答1:


The problem is that scanf("%d", &t) leaves a newline in the input buffer, which is only consumed by scanf("%c", &a) (and hence a is assigned a newline character). You have to consume the newline with getchar();.

Another approach is to add a space in the scanf() format specifier to ignore leading whitespace characters (this includes newline). Example:

for(i=0; i<t; i++)
{
    printf("enter a: ");
    scanf(" %c",&a);

    printf("enter b: ");
    scanf(" %c",&b);
}

If you prefer using getchar() to consume newlines, you'd have to do something like this:

for(i=0; i<t; i++)
{
    getchar();
    printf("enter a: ");
    scanf("%c",&a);

    getchar();
    printf("enter b:");
    scanf("%c",&b);
 }

I personally consider the former approach superior, because it ignores any arbitrary number of whitespaces, whereas getchar() just consumes one.




回答2:


By seeing your code it's perfect it should read T times A and B but it replaces A and B every time the for each loop.

Use array or hash table to store effectively




回答3:


Some formats used with scanf makes a newline trimmed from stdin but others don't. Reading using "%d" falls into latter category. You need to read a newline '\n' before reading into

scanf("%c", &a);


来源:https://stackoverflow.com/questions/24099976/read-two-characters-consecutively-using-scanf-in-c

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