c - 尝试在 C 中调用自定义函数,但 scanf() 导致出现问题

标签 c function scanf

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

#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 不会运行。

最佳答案

始终在 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

关于c - 尝试在 C 中调用自定义函数,但 scanf() 导致出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13337931/

相关文章:

jquery - scrolltofixed 限制问题和闪烁

c - 为什么 scanf 在这里跳过输入?

c - 以相同的优先级移位/归约

c++ - 在 Windows 7 中交叉编译 C 和 C++ 应用程序,在 linux 下使用 MinGW

c - sscanf 不能正常工作?

algorithm - 生成随机函数(不是数字!)——如何实现

具有相同名称的 C 函数返回不同的数据值

input - 在 D 中是否有比 scanf() 更丑陋的输入方式?

c++ - fscanf 不能正确处理字符串

c - 如何评估宏参数中的逻辑语句