Răzvan Flavius Panda
Răzvan Flavius Panda

Reputation: 22116

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

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

Upvotes: 2

Views: 2281

Answers (2)

Gow.
Gow.

Reputation: 55

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;
}

Upvotes: 1

Răzvan Flavius Panda
Răzvan Flavius Panda

Reputation: 22116

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.

Upvotes: 3

Related Questions