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

Announcement

Collapse
No announcement yet.

Why is this simple C program skipping a scanf?

Collapse
X
 
  • 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:

    Code:
    #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:

    Code:
    Enter 3 numbers with decimals: 2.325
    1.256
    1.445
    
    Now enter an integer: 5
    
    Finally, enter a single character:
    
    Doubles as Floats:
    -92559604392960731000000000000000000000000000000000000000000000.00
    -92559604306135282000000000000000000000000000000000000000000000.00
    -92559604324237887000000000000000000000000000000000000000000000.00
    
    Integer with padded zeros:
    000005
    
    Inputted character "
    " as number:
    10
    
    Sum of values:
    -277678813023333900000000000000000000000000000000000000000000000.00
    
    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!||||

    Comment


    • #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.

      Comment

      Working...
      X