Thread: scanf doesn't like order of input

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    182

    scanf doesn't like order of input

    Yes, I know I shouldn't be using scanf. I'd still like to know why this doesn't work though.

    With scanf reading into the float variable first, it shows up as 0.0000... but the double variable shows up fine.

    With scanf reading the double variable first, both numbers print out exactly as they should. Why is this?

    Code:
    #include <stdio.h>
    
    union floatingPoint {
    	float f;
    	double d;
    	long double x;
    } test[ 3 ];
    
    int main()
    {
    	int i;
    
    	scanf( "%f%lf", &(test[ 0 ].f), &(test[ 0 ].d) );
    	printf( "%f %lf\n", test[ 0 ].f, test[ 0 ].d );
    
    	return 0;
    }

    Code:
    eugene@eugene-laptop:~/cfiles$ ./a.out
    1 1
    0.000000 1.000000

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Perhaps it has something to do with using a union rather than a struct.
    Largest one, or last one wins (basically).

    Double first only "works" with small integers, because the LSW of the double is all zeros anyway.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    182
    ahh, thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Input class project (again)
    By Elysia in forum C++ Programming
    Replies: 41
    Last Post: 02-13-2009, 10:52 AM
  2. Input and Scanf
    By DAaaMan64 in forum C Programming
    Replies: 3
    Last Post: 01-14-2009, 06:56 PM
  3. Scanf String
    By Demipimp in forum C Programming
    Replies: 9
    Last Post: 12-05-2008, 11:12 AM
  4. validating input using scanf
    By Axel in forum C Programming
    Replies: 6
    Last Post: 09-12-2005, 08:23 AM
  5. h/w help
    By helpme in forum C Programming
    Replies: 20
    Last Post: 10-21-2003, 09:36 AM