views:

265

answers:

4

To read an int using scanf we use:

scanf("%d",&i);

What if i is long not int??

Note: when using %d with long it gives me an irritating warning..

Thanks!

+1  A: 
scanf("%ld", &i);

You can also use "%Ld" for a long long (and depending on your compiler, sometimes also "%lld").

Take a look at the Conversions section of the scanf man page for more. (Just Google it if your system doesn't have manpages).

Vineet
And doesn't that same man page say that the things you are reading into need to be passed to scanf as pointers?
anon
For `long long (int)`, "%lld" is standard (the "L" modifier is meant for `long double`, so "%Ld" isn't standard, though I don't doubt that some implementations allow it). BSD flavours once used the "q" length modifier for a "quadword", which is just a 64-bit value, and I'm reasonably sure it is still accepted in some BSD-based implementations. Microsoft created the "I64" and "I32" length modifiers to specify a 64-bit and a 32-bit integer respectively, so "%I64d" would be valid in that case. In other words, `long long` is a mess of confusion when it comes to the formatted I/O functions. :P
Dustin
+3  A: 

Just use

long l;

scanf("%ld", &l);

it gives me an irritating warning..

That warning is quite right. This is begging for stack corruption.

jpalecek
Whereas your code simply gives undefined behaviour. You need to give scanf the address of the variable being read into.
anon
+6  A: 

For gods sake:

long n;
scanf( "%ld", & n );
anon
To add to Neil's answer, you can't rely on something like "%d" to read a `long int` because that specifies an `int` rather than a `long (int)`. Not only that, `int` on some 64-bit systems is 32 bits in size while `long (int)` is 64 bits in size. In other words, you'd be reading a 32-bit integer into what is meant to be a 64-bit storage location. An example would be reading 2147483649. Since the 32-bit value is read into a 64-bit location, the other 32 bits are left with whatever values were present, so you might get something like 6442450945 if you had 4294967296 stored in there originally.
Dustin
+1  A: 

Each conversion specifier expects its corresponding argument to be of a specific type; if the argument's type does not match the expected type, then the behavior is undefined. If you want to read into a long with scanf(), you need to use the %ld conversion specifier:

long i;
scanf("%ld", &i);

Check the online draft C standard (.pdf file), section 7.19.6.2, paragraph 11 for a complete listing of size modifiers and expected types.

John Bode