问题
This code gives me warnings:
$ cat test.c
#include<stdio.h>
#include<time.h>
int main() {
time_t t;
scanf("%lld", &t);
printf("%lld\n", t);
return 0;
}
$ gcc test.c -o test
test.c: In function ‘main’:
test.c:7: warning: format ‘%lld’ expects type ‘long long int *’, but argument 2 has type ‘time_t *’
test.c:8: warning: format ‘%lld’ expects type ‘long long int’, but argument 2 has type ‘time_t’
$
Apart from the warnings, the code works as expected.
What should I do to not get the warnings on compilation (no compiler pragma tricks please)?
回答1:
The exact type of time_t
depends on your platform and OS. It's still quite often 32 bit (either int
or long
), not 64, and some even use floats. The correct thing to do is to read into a known-size integer (either int
or long long
) and then assign the value to a time_t
as a second step.
回答2:
You need the format to match the time_t definition of your system. Compile with
gcc test.c -o test --save-temps
then
grep time_t test.i|grep typedef
Most likely, this will tell you that time_t is "long int", so you need to scan it with "%ld".
回答3:
First, your compiler is right: nothing guarantees that time_t is actually a 64-bit signed integer. It could be a 32-bit integer or even a floating-point value, depending on the platform.
Now, if you're absolutely, positively sure that time_t
is a long long
on your platform, and you want to avoid the formatting warnings, you can do:
time_t t;
scanf("%lld", (long long *) &t);
printf("%lld\n", (long long) t);
回答4:
Use a known size of integer with scanf() and then convert the result to time_t
:
#include <stdio.h>
#include <time.h>
int main()
{
long long llv;
time_t t;
scanf("%lld", &llv);
t = llv;
printf("%lld\n", (long long)t);
return 0;
}
In this example, it doesn't seem to buy you much, but if you wanted to pass the variable t
to some of the time-manipulation functions, then you would have the correct type to work with.
If you look at the linked URL for (the POSIX extended version of) scanf()
, you'll see that there is no mention of time_t
type there. Thus, any mechanism to read time_t
values with scanf()
has to be somewhat less than straight-forward. Ditto, anything that prints time_t
values is also somewhat less than straight-forward.
来源:https://stackoverflow.com/questions/4171478/how-to-read-data-into-a-time-t-variable-using-scanf