我继续学习C,在这个阶段我有一些我不清楚的事情。
当我编写一个程序时,有几个printf();
,最后,我要求用户按Enter键完成程序,我必须写getchar();
两次,因为当我写一次这是行不通的。我只在程序结束时使用getchar();
,而不是其他地方。
我在Ubuntu上工作。我用C写作。
这是我的最新作品:
#include<stdio.h>
main()
{
int m,n,r,k,q,l;
printf("This program will help you to find GCD & LCM of 2 non-negative integers\n");
printf("Now, you'll be asked to enter your integers, press Enter to continue");
getchar();
printf("Enter first integer:");
scanf("%i", &m);
printf("Enter second integer:");
scanf("%i", &n);
while(m<0 || n<0)
{
printf("The integers cannot be negative! You'll be asked to enter integers again.\n");
printf("Enter first integer:");
scanf("%i", &m);
printf("Enter second integer:");
scanf("%i", &n);
}
while(m==0 && n==0)
{
printf("Both of the integers cannot be zero at the same time! You'll be asked to enter integers again.\n");
printf("Enter first integer:");
scanf("%i", &m);
printf("Enter second integer:");
scanf("%i", &n);
}
if(n>m)
{
int b;
b=n;
n=m;
m=b;
}
r=m%n;
if(r==0)
{
printf("The GCD of these integers is %i\n", n);
printf("The LCM of these integers is %i\n", m);
printf("Press Enter to finish");
getchar();
getchar();
return 0;
}
k=n%r;
while(k>0)
{
r=k;
k=q;
}
l=(m*n)/r;
printf("The GCD of these integers is %i\n", r);
printf("The LCM of these integers is %i\n", l);
printf("Press Enter to finish");
getchar();
getchar();
return 0;
}
答案 0 :(得分:2)
您需要2 getchar()
的原因是
scanf()
调用让 ENTER 在缓冲区中等待getchar()
“吃” ENTER getchar()
等待输入。要正确处理用户输入,请使用更简单fgets()
的{{1}}和sscanf()
个实例。为这些函数定义缓冲区,例如
scanf()
然后将<{1}}次来电替换为
char buffer[1000];
将来您可能还需要检查scanf()
的返回值以检测无效输入,例如 foo42 ENTER
fgets(buffer, sizeof buffer, stdin);
sscanf(buffer, "%d", &n);
编辑(使用sscanf()
而非if (sscanf(buffer, "%d", &n) != 1) /* invalid input */;
甚至更好 - 感谢@Scooter)
strtol()