【问题标题】:scanf doesn't take input in debug mode in eclipse?scanf 在 Eclipse 的调试模式下不接受输入?
【发布时间】:2017-05-25 11:41:28
【问题描述】:

首先还有另一个同名的问题,但那里提供的解决方案对我不起作用。 Other question

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

int main()
{
    int a, b, c;
    fflush(stdout);//suggested solution in other question
    scanf("%d%d%d", &a, &b, &c);
    printf("Values entered: %d %d %d\n", a, b, c);
    return 0;
}

当我正常运行时,代码运行良好。

输出

1 2 3
Values entered: 1 2 3

但是当我在调试模式下运行时,什么都没有打印出来。当我将鼠标悬停在变量上时,它们具有这些值。

一个:56

b : 6422420

c : 6422420

建议的另一个解决方案是将此代码放在 main 方法的开头。

    int ch;
    while ((ch = getchar()) != '\n' && ch != EOF); //suggested solution #1

帖子中建议的两种解决方案都不适合我。我分别尝试了它们。

编辑

操作系统:Windows 10

编译器:MinGW

【问题讨论】:

  • 什么编译器(Eclipse 不是编译器)以及您使用的是什么操作系统?
  • 我建议在命令行上编译。 Eclipse 只是对你隐藏了一些东西。
  • C 和 C++ 是不同的语言,在询问您的程序时不要同时指定两者。

标签: c++ c eclipse


【解决方案1】:

我建议在scanf 格式中使用空格,并测试其返回计数,因此:

a = b = c = 0; // better to clear variables, helpful for debugging at least
int cnt = 0;
if ((cnt=scanf(" %d %d %d", &a, &b, &c)) == 3) {
  /// successful input
  printf("Values entered: %d %d %d\n", a, b, c);
}
else { 
  /// failed input
  printf("scanf failure cnt=%d error %s\n", cnt, strerror(errno));
}
fflush(NULL); // probably not needed, at least when stdout is a terminal

在使用之前仔细阅读scanf(以及每个库函数)的文档。

顺便说一句,Eclipse 只是一个IDE 或美化source code editor,您的编译器可能是GCCClang(您可能可以配置您的IDE 以将适当的选项传递给您的编译器)。而scanf 本身是在您的C standard library 中实现的(在您的操作系统kernel 之上)。

但是您确实需要在编译器中启用所有警告和调试信息(如果使用 GCC,请使用 gcc -Wall -Wextra -g 进行编译)并学习如何使用您的 debugger gdb(断点、逐步、变量查询、回溯...)

您可能想使用fflush,并且您应该在终端中编译和运行您的程序(而不是在 Eclipse 下,它隐藏了很多对您有用的东西)。

【讨论】:

  • 我试过你的代码。它跳到perror("scanf failure"); 部分而不输入if 条件。注意:工作正常。这仅在调试模式下发生。
  • 但是你仔细阅读scanf的文档了吗?顺便说一句,我稍微改进了我的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-09
  • 2019-10-24
  • 1970-01-01
相关资源
最近更新 更多