[英]calling main function in C
#define f(x) (x*(x+1)*(2*x+1))/6
void terminate();
main()
{
int n,op;
char c;
printf("Enter n value\n");
scanf("%d",&n);
op=f(n);
printf("%d",op);
printf("want to enter another value: (y / n)?\n");
scanf("%c",&c); // execution stops here itself without taking input.
getch();
if(c=='y')
main();
else
terminate();
getch();
}
void terminate()
{
exit(1);
}
在上面的程序中,我要从用户那里接受输入,直到他输入n
值为止。 为此,我试图重复调用main()
函数。 如果在C中合法,我想知道程序为什么在scanf("%c",&c)
处终止,如注释行所示。 有人请帮忙。
您永远不要从程序内部调用main
。 如果需要运行更多,请在其中一次使用while
循环。
您的执行停止,因为默认情况下终端中的stdin是行缓冲的。 同样,您没有使用getch
的返回值。
int main()
{
int n,op;
char c;
do {
printf("Enter n value\n");
scanf("%d",&n);
op=f(n);
printf("%d",op);
printf("want to enter another value: (y / n)?\n");
scanf("%c",&c);
} while (c == 'y')
return 0;
}
你先有
scanf("%d",&n);
您必须按Enter键才能接受该号码。
以后你有
scanf("%c",&c);
这里有一个问题,就是对scanf
的第一次调用将Enter键留在输入缓冲区中。 因此,稍后的scanf
调用将读取该内容。
通过稍微更改第二个scanf
调用的格式字符串,就可以轻松解决此问题:
scanf(" %c",&c);
/* ^ */
/* | */
/* Note space here */
这告诉scanf
函数跳过前导空格 ,其中包括换行符,例如Enter键。
这是合法的,但过一会儿就会出现STACKOVERFLOW(双关语是故意的)。 您需要的是一个循环:
while (1) {
printf("Enter n value\n");
scanf("%d",&n);
op=f(n);
printf("%d",op);
printf("want to enter another value: (y / n)?\n");
scanf("%c",&c); // execution stops here itself without taking input.
getch();
if(c != 'y')
break;;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.