Web Analytics Made Easy -
StatCounter Why is this simple C program skipping a scanf? - CodingForum


No announcement yet.

Why is this simple C program skipping a scanf?

  • Filter
  • Time
  • Show
Clear All
new posts

  • Why is this simple C program skipping a scanf?

    Preface: yes this is a homework assignment but I've already done it and there's one "bug" that seems to be keeping me down... I have a PHP background so some of C's quirks really gets me sometimes...

    Anywho this program compiles and runs correctly but it seems to skip the third scanf() call (the one that asks to input a character) and instead skips to the output. Here's the code and an example execution:

    #include <stdio.h>
    int main(void){
    	// declare variables
    	double doub1, doub2, doub3, sum;
    	int integer1;
    	char char1;
    	// input the numbers
    	printf("Enter 3 numbers with decimals: ");
    	scanf("%f%f%f", &doub1, &doub2, &doub3);
    	printf("\nNow enter an integer: ");
    	scanf("%d", &integer1);
    	printf("\nFinally, enter a single character: ");
    	scanf("%c", &char1);
    	// output 3 doubles as floats
    	printf("\n\nDoubles as Floats:\n%6.2f\n%6.2f\n%6.2f", doub1, doub2, doub3);
    	// output integer
    	printf("\n\nInteger with padded zeros:\n%06d", integer1);
    	// output character
    	printf("\n\nInputted character \"%c\" as number:\n%d", char1, char1);
    	// add and print final value
    	sum = doub1 + doub2 + doub3 + integer1 + char1;
    	printf("\n\nSum of values:\n%8.2f\n\n", sum);
    	return 0;
    Sample execution:

    Enter 3 numbers with decimals: 2.325
    Now enter an integer: 5
    Finally, enter a single character:
    Doubles as Floats:
    Integer with padded zeros:
    Inputted character "
    " as number:
    Sum of values:
    Press any key to continue . . .
    What's the deal with it skipping the third scanf? Thanks!

  • #2
    Use %s instead of %c.
    ||||If you are getting paid to do a job, don't ask for help on it!||||


    • #3
      Nevermind, I found the problem. I needed to flush the input stream character by putting a space before the "%x" in the two scanfs after the initial one.