【问题标题】:calling main function in C在 C 中调用主函数
【发布时间】:2014-02-21 17:23:33
【问题描述】:
#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) 处终止,如注释行所示。 有人,请帮忙。

【问题讨论】:

  • OT:至少是int main(void)。并假设terminate() 不打算接受任何参数,它应该是void terminate(void)
  • @alk - 进行了更改,但问题仍然存在。

标签: c main


【解决方案1】:

你不应该在你的程序中调用main。如果您需要更多地运行它,请在其中使用 while 循环。

您的执行将停止,因为默认情况下终端中的标准输入是行缓冲的。此外,您没有使用来自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;
}

【讨论】:

  • 我猜getch 调用是获取并丢弃缓冲区中scanf 调用留下的换行符。在这种情况下不需要哪个(如您在代码 sn-p 中所示)。
  • @JoachimPileborg 他只调用scanf,默认情况下会丢弃所有空白字符。没必要。
  • 扫描字符时不会。
  • @JoachimPileborg 是的。下一个scanf 调用会扫描一个整数,所以没关系。我会使用fgets,然后使用缓冲区中的sscanf
【解决方案2】:

你先有

scanf("%d",&n);

您必须按 Enter 键才能接受该数字。

后来你有

scanf("%c",&c);

这里有一个问题,即第一次调用scanfEnter 键留在输入缓冲区中。所以后面的scanf 调用会读取到。

这很容易解决,只需稍微更改第二个scanf 调用的格式字符串即可:

scanf(" %c",&c);
/*     ^           */
/*     |           */
/* Note space here */

这告诉scanf 函数跳过前导空格,其中包括换行符,如Enter 键离开。

【讨论】:

  • @hacks 这是我的头像,是的,虽然不是动画。 :) 得到它作为对Kickstarter pledge 的奖励。 :)
  • 事实上它看起来很像你(正如我在你的旧头像中看到的那样),这就是我问你的原因。 :)
  • @hacks 是的,艺术家真的“抓住了我”:)
【解决方案3】:

这是合法的,但一段时间后您会遇到 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;;
}

【讨论】:

    猜你喜欢
    • 2014-10-02
    • 2016-02-24
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 2015-04-21
    相关资源
    最近更新 更多