Scanf doesn't appear to work in debug mode in Eclipse CDT with GDB

邮差的信 提交于 2019-12-14 02:05:44

问题


When running this code in debug mode:

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

int main()
{
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    printf("Values entered: %d %d %d\n", a, b, c);
    return EXIT_SUCCESS;
}

The program would not request any user input and would just output:

Values entered: 18 78 2130026496


回答1:


I had the same problem. Figured out that you have to clear output buffer if a newline character is used or if an input function is used. So, do this way..

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

int main()
{
    int a, b, c;
    fflush(stdout);//Clears the stdout buffer
    scanf("%d%d%d", &a, &b, &c);
    printf("Values entered: %d %d %d\n", a, b, c);
    return EXIT_SUCCESS;
}



回答2:


It seems the problem was caused by GDB writing to stdin the following line before scanf was run:

18-list-thread-groups --available

And scanf("%d%d%d", &a, &b, &c); was interpreting that line as int's instead of waiting for user input.

The current solution I use is to clear stdin at the beginning of the program using:

int ch;
while ((ch = getchar()) != '\n' && ch != EOF);

I know that it is kind of a hack but I searched for over an hour for a solution and I couldn't find any. I hope this helps someone.



来源:https://stackoverflow.com/questions/12126703/scanf-doesnt-appear-to-work-in-debug-mode-in-eclipse-cdt-with-gdb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!