This question already has answers here:
scanf() leaves the new line char in the buffer
                                
                                    (4个答案)
                                
                        
                                2年前关闭。
            
                    
如果我尝试以下操作:

int anint;
char achar;

printf("\nEnter any integer:");
scanf("%d", &anint);
printf("\nEnter any character:");
scanf("%c", &achar);
printf("\nHello\n");
printf("\nThe integer entered is %d\n", anint);
printf("\nThe char entered is %c\n", achar);


它允许输入一个整数,然后完全跳过第二个scanf,这确实很奇怪,因为当我交换两个(第一个char scanf)时,它可以正常工作。到底怎么了?

最佳答案

使用scanf读取输入时,按回车键后将读取输入,但scanf不会使用回车键生成的换行符,这意味着下次您从标准输入中读取char时,换行,准备阅读。

一种避免的方法是使用fgets以字符串形式读取输入,然后使用sscanf提取所需内容:

char line[MAX];

printf("\nEnter any integer:");
if( fgets(line,MAX,stdin) && sscanf(line,"%d", &anint)!=1 )
   anint=0;

printf("\nEnter any character:");
if( fgets(line,MAX,stdin) && sscanf(line,"%c", &achar)!=1 )
   achar=0;


使用换行符的另一种方法是scanf("%c%*c",&anint);%*c将从缓冲区读取换行符并将其丢弃。

您可能需要阅读以下内容:

C FAQ : Why does everyone say not to use scanf?

10-08 08:20
查看更多