【问题标题】:Trying to call custom function in C but scanf( ) is causing an issue尝试在 C 中调用自定义函数但 scanf() 导致问题
【发布时间】:2012-11-12 03:15:55
【问题描述】:

你能说出这里出了什么问题吗?

#include <stdio.h>
#include <stdlib.h>

int test (void)
{
    int i;
    printf("Enter a number: ");
    scanf("%d",&i);

    return i;
}

int main (void)

{

   test();

   return 0;
}

这只是一个简单的示例,但由于某种原因,除非我摆脱 scanf,否则 main 不会运行。

【问题讨论】:

  • 不运行是什么意思?它将等待输入,如果这就是您的意思。
  • 只是坐在那里无所事事? :) 输入 1
  • 也尝试打印一些东西。在 scanf() 之后,输入 '1' 并添加语句 printf()。这样你就会看到你的程序很好。
  • 编译器运行时没有任何反应,但没有任何显示。它只是运行并运行,直到我强行关闭它。如果我注释掉scanf(),至少会出现“输入一个数字”。
  • 我尝试输入 1 并显示“输入一个数字:”。就好像它在倒退一样。

标签: c function scanf


【解决方案1】:

始终在 printf 字符串的末尾使用'\n'。这使得输出缓冲区刷新并打印字符串。在您的程序中添加更多打印。 你可以像下面这样重写你的程序,打印将帮助你了解你的程序发生了什么。

#include <stdio.h>
#include <stdlib.h>

int test (void)
{
    int i;
    printf("Enter a number: \n");
    scanf("%d",&i);
    printf("You just eneterd : %d\n",i);
    return i;
}

int main (void)

{
   printf("About to call test() \n");
   test();
   printf("Done calling test() \n");
   return 0;
}

最好买一本好的 C 编程书来理解这些基本知识。我建议The C programming language

【讨论】:

    【解决方案2】:

    我认为您必须使用 fflush() 或在 printf 函数末尾使用 '\n' 字符,这最终会刷新 std 输出缓冲区。为了检查,只需在读取值后使用 printf() 打印变量的值。

    希望对您有所帮助....

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 1970-01-01
      • 2014-05-03
      • 1970-01-01
      相关资源
      最近更新 更多