在C中调用主函数
在上面的程序中,我想从用户那里获取输入,直到他输入一个在C中调用主函数,c,main,C,Main,在上面的程序中,我想从用户那里获取输入,直到他输入一个n值。 为此,我尝试反复调用main()函数。如果它在C中是合法的,我想知道为什么程序终止于scanf(“%C”,&C),如注释行所示。 有人,请帮忙。您不应该在程序中调用main。如果您需要多次运行它,请在其内部使用循环 执行停止,因为默认情况下,终端中的stdin是行缓冲的。另外,您没有使用getch中的返回值 #define f(x) (x*(x+1)*(2*x+1))/6 void terminate(); main() { i
n
值。
为此,我尝试反复调用main()
函数。如果它在C中是合法的,我想知道为什么程序终止于scanf(“%C”,&C)
,如注释行所示。
有人,请帮忙。您不应该在程序中调用
main
。如果您需要多次运行它,请在其内部使用循环
执行停止,因为默认情况下,终端中的stdin是行缓冲的。另外,您没有使用getch
中的返回值
#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);
}
这是合法的,但过一段时间你会有堆栈溢出(双关语)。
您需要的是一个循环:
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;
}
你先有
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;;
}
您必须按Enter键才能接受该号码
以后你有
scanf("%d",&n);
这里有一个问题,那就是对scanf
的第一次调用将Enter键留在输入缓冲区中。因此稍后的scanf
调用将读取该值
这很容易解决,只需稍微更改第二次scanf
调用的格式字符串:
scanf("%c",&c);
这告诉scanf
函数跳过前导空格,其中包括回车键leaves之类的换行符。OT:至少是int main(void)
。假设terminate()
不打算接受任何参数,它应该是void terminate(void)
@alk-进行了更改,但问题仍然存在。我猜getch
调用是获取并丢弃缓冲区中scanf
调用留下的换行符。这在本例中是不需要的(如您在代码片段中所示)。@JoachimPileborg他只调用scanf
,默认情况下会丢弃所有空白字符。不需要。扫描角色时不需要。@JoachimPileborg是的。不过,下一个scanf
调用会扫描一个整数,所以没问题。我会使用缓冲区中的fgets
,然后使用sscanf
。@haccks这是我的化身是的,但不是动画。:)作为奖励,我得到了它。:)事实上,它看起来非常像你(正如我在你的旧头像中看到的),这就是我问你的原因。:)@哈克斯是的,这位艺术家真的“抓住了我”:
scanf(" %c",&c);
/* ^ */
/* | */
/* Note space here */