这个问题已经有了答案:
C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]
7个答案
我学的是C编程。我写了一个奇怪的循环,但是当我在%c中使用scanf()时它不工作。

#include<stdio.h>
void main()
{
    char another='y';
    int num;
    while ( another =='y')
    {
        printf("Enter a number:\t");
        scanf("%d", &num);
        printf("Sqare of %d is : %d", num, num * num);
        printf("\nWant to enter another number? y/n");
        scanf("%c", &another);
    }
}

但如果我在这段代码中使用%s,例如scanf("%s", &another);,那么它就可以正常工作。为什么会发生这种情况?知道吗?

最佳答案

%c转换从输入中读取下一个字符,而不管它是什么。在本例中,您以前使用%d读取过一个数字。您必须按enter键才能读取该数字,但是您没有做任何事情来读取输入流中的新行。因此,当您执行%c转换时,它会从输入流中读取新行(不需要等待您实际输入任何内容,因为已经有输入等待读取)。
当您使用%s时,它会跳过任何前导空白以获取除空白以外的字符。它将新行视为空白,因此它隐式跳过等待的新行。既然(大概)没有其他东西等待阅读,它就会继续等待你输入一些东西,正如你显然希望的那样。
如果要使用%c进行转换,可以在转换前加上格式字符串中的空格,这样也可以跳过流中的任何空白。

07-24 09:46
查看更多