Scanf doesn't appear to work in debug mode in

2019-07-14 05:58发布

问题:

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.