This is my program when I learn scanf function:
#include <stdio.h>
int main(int argc, char *argv[]) {
int day, year;
char monthName[20];
printf("separate day by /\n");
scanf("%d/%s/%d", &day, monthName, &year);
printf("%d %s %d\n", day, monthName, year);
printf("separate day by blank\n");
scanf("%d%s%d", &day, monthName, &year);
printf("%d %s %d\n", day, monthName, year);
return 0;
}
The input and output are below:
separate day by /
3/Dec/2016
3 Dec/2016 0
separate day by blank
3 Dec 2016
3 Dec 2016
Why does the second / mark appears and so does the zero char? Is there any way or tools to analysis such problem?
It's because your %s
is getting everything after the first /
character. So when your %d
starts to read, there is nothing left.
You can clearly understand that output by doing this:
printf("separate day by /\n");
scanf("%d/%s/%d", &day, monthName, &year);
printf("%d---%s---%d\n", day, monthName, year);
Which yields:
separate day by /
3/Dec/2016
3---Dec/2016---0
The reason scanf
is not respecting the second /
as you expected is because %s
doesn't stop at the /
, it stops only on whitespace characters. Check this from the docs:
Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments