3

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.

4

3 回答 3

9

问题是scanf("%d", &t)在输入缓冲区中留下一个换行符,它只被消耗scanf("%c", &a)(因此a被分配一个换行符)。您必须使用getchar();.

另一种方法是在scanf()格式说明符中添加一个空格以忽略前导空白字符(这包括换行符)。例子:

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

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

如果您更喜欢使用getchar()换行符,则必须执行以下操作:

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

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

我个人认为前一种方法更好,因为它忽略了任意数量的空格,而getchar()只消耗一个。

于 2014-06-07T17:54:23.707 回答
0

通过查看您的代码,它是完美的,它应该读取 T 次 A 和 B,但每次循环时它都会替换 A 和 B。

使用数组或哈希表有效存储

于 2014-06-07T17:56:02.737 回答
0

使用的某些格式scanf会修剪换行符,stdin但其他格式不会。阅读使用"%d"属于后一类。您需要在阅读'\n'之前阅读 换行符

scanf("%c", &a);
于 2014-06-07T18:01:22.097 回答