Search code examples
cubuntuscanfgetchar

skipped trouble with getchar and scanf


I recently started to program in C and im having trouble with this code:

#include <stdio.h>
#include <stdlib.h>
#define PI 3.1416

int main () {
    float x;
    int y;

    x = PI;

    printf("Enter y: ");
    scanf(" %i", &y);
    printf("The new value of y is: %i.\n\n",y);

    x = x * y;
    printf("The new value of x is: %f.\n\n",x);


    getchar();
    return 0;
}

the problem appears with the getchar() at the end, the program shutdown and doesnt wait for the input. I have found a solution i dont like at all and is by adding 2 times getchar(). Is there any way around it?, im using ubuntu so system("pause") is not an option


Solution

  • The scanf command does not consume the Enter key that you pressed after entering y. So the getchar() happily consumes it.

    One solution is to consume the rest of the input line after reading y; the code for that looks like:

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

    Although there are other options for pausing at the end of a program, this is probably a good idea anyway because it will be necessary if you later expand your program to expect string or character input.