getchar的相关问题请教
如图1所示,有两个getchar分别跟在scanf后面;
图1
如图2所示,把两个getchar移到程序的最后面
图2
两个图运行后的结果是,图1中的程序会自动退出,图2中的程序会等待用户输入回车程序才结束。
我想问的问题是,为什么getchar移动了一下位置,执行结果竟然会不相同呢?
附代码:
#include "stdafx.h"
#include <string.h>
#define DENSITY 62.4
int _tmain(int argc, _TCHAR* argv[])
{
float weight,volume;
int size,letters;
char name[40];
printf("Hi!What's your first name?\n");
scanf("%s",name);
printf("%s,what's your weight in pounds?\n",name);
scanf("%f",&weight);
getchar();
size=sizeof name;
letters=strlen(name);
volume=weight/DENSITY;
printf("Well,%s,your volume is %2.2f cubic feet.\n",
name,volume);
printf("Also,your first name has %d letters,\n",letters);
printf("and we have %d bytes to store it in.\n",size);
getchar();
getchar();
return 0;
}
[解决办法]
Hi! What's your first name?
bill<cr> // scanf("%s", name);
bill, what's your weight in pounds?
1.1<cr> // scanf("%f", &weight); getchar();
<cr> // getchar();
输入流为:
bill<cr 1>1.1<cr 2><cr 3>
scanf("%s", name);从流中提取bill,遇到<cr 1>停止,<cr 1>由于没有提取,仍在流中;
scanf("%f", &weight);(略过<cr 1>,因为它不是float),提取1.1,遇到<cr 2>停止,<cr 2>没有提取,仍在流中;
getchar();提取<cr 2>;
getchar();提取<cr 3>;
程序结束。