Odd Behavior for scanf("%c", &var)

This is a discussion on Odd Behavior for scanf("%c", &var) within the C Programming forums, part of the General Programming Boards category; I am writing a small program that requires the user to input a char on two occasions. The two functions ...

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    8

    Odd Behavior for scanf("%c", &var)

    I am writing a small program that requires the user to input a char on two occasions. The two functions below are called one after the other in main().

    Code:
    float getShares(float number)
    {
    	float answer;
    	char sharesCap;
    	
    	printf( "Enter shares cap: " );
    	scanf( "%c", &sharesCap );...
    	
    	return answer;
    }
    
    float getEarnings(float number)
    {
    	float answer;
    	char earningsCap;
    	
    	printf( "Enter earnings cap: " );
    	scanf( "%c", &earningsCap );...
    	
    	return answer;
    }
    The code compiles with no errors, and runs fine with one exception: The first scanf() fires but does not wait for the user to input their text. Instead, here is what I am seeing in the terminal:

    "Enter shares cap: Enter earnings cap: "

    The first scanf() doesn't wait for me to enter a character. What gives? Is this a common problem? Solutions???

    Thanks, Irno.

  2. #2
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    scanf leaves newlines in the input buffer, so I suspect you have a previous call to scanf before you call those functions. Show more code.

  3. #3
    Registered User
    Join Date
    Jun 2009
    Posts
    8
    Yes, I do. Here's what main() looks like before calling getShares():
    Code:
    printf("Enter the dividend pmt: ");
    scanf("%f", &div);
    
    printf("Enter shares outstanding: ");
    scanf("%f", &shares);
    	
    printf("Enter co earnings: ");
    scanf("%f", &earnings);

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    Clear the input buffer after each call to scanf (do NOT use fflush(stdin) though).

    Cprogramming.com FAQ > Flush the input buffer

  5. #5
    Registered User
    Join Date
    Jun 2009
    Posts
    8
    that seems to do the trick. thanks, memloop

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. odd function is odd
    By plain in forum C Programming
    Replies: 3
    Last Post: 10-05-2009, 01:01 AM
  2. Help C program that reads Odd numbers and evens
    By Cyberman86 in forum C Programming
    Replies: 4
    Last Post: 02-27-2009, 11:59 AM
  3. adding odd numbers only
    By CheyenneWay in forum C++ Programming
    Replies: 12
    Last Post: 05-06-2004, 01:22 AM
  4. new type: even or odd
    By nbo10 in forum C++ Programming
    Replies: 7
    Last Post: 09-05-2003, 12:17 PM
  5. Homework help
    By Jigsaw in forum C++ Programming
    Replies: 2
    Last Post: 03-06-2002, 05:56 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21