scanf与fgets混用导致fgets无法读取用户输入的问题咨询
为啥输入全名时程序直接跳过了?
给5岁娃的大白话解释
想象你有个装小纸条的盒子,每次你输入完内容按回车,就相当于把「你输的内容+一张写着“回车”的小纸条」一起放进盒子里。
- 前面输年龄、GPA、名字的时候,程序用的
scanf是个“挑食”的小家伙:它只把盒子里的数字、单词拿出来用,那张“回车”小纸条就留在盒子里没管。 - 到输全名的时候,程序换了
fgets来拿东西,它一打开盒子,先看到里面剩的“回车”小纸条,就以为你已经把要输的东西放完了,直接把这张纸条当全名拿出来,所以就直接输出空的啦。
具体技术原因
scanf的%d(读整数)、%lf(读浮点数)、%s(读单词)这些格式符,只会读取符合要求的内容,读取完成后,输入时按下的回车符会留在标准输入缓冲区(stdin)里。fgets是从缓冲区里读取内容,它会一直读到回车符为止,还会把回车符一起读进变量里。当scanf用完后,缓冲区里只剩之前残留的回车符,fgets一读到这个回车符就停止了,所以fullname里只有一个回车符,输出时就显示空行。
解决办法
在调用fgets之前,把缓冲区里残留的回车符清空就行,加一行代码:
// 把缓冲区里剩下的回车符都吃掉 while(getchar() != '\n');
你的代码和运行结果
原代码
#include <stdio.h> int main() { /* some codes do not work as expected. How so? */ int age; printf("Enter your age: "); /* asking which type of data we want from user */ scanf("%d", &age); printf("You are %d years old \n", age); double gpa; printf("Enter your gpa: "); scanf("%lf", &gpa); /* what is lf? */ printf("Your gpa is %lf \n", gpa); char name[20]; printf("Enter your name: "); /* no need for ambersand */ scanf("%s", name); printf("Your name is %s \n", name); /* issue with scanf is that everything after scan is ignored */ char fullname[20]; printf("Enter your full name: "); /* fgets does take space included input no need for ambersand */ fgets(fullname, 20, stdin); printf("Your name is %s \n", fullname); /* issue with scanf is that everything after scan is ignored */ return 0; }
运行输出
Enter your age: 5 You are 5 years old Enter your gpa: 3.6 Your gpa is 3.600000 Enter your name: papa Your name is papa Enter your full name: Your name is
内容的提问来源于stack exchange,提问作者Mathology
相关产品推荐
相关产品推荐

