简体   繁体   中英

C scanf skipping second time

I have read about placing whitespace in front of scanf but I everything I try does not work. I am trying to read in two sets of three integers. The first scanf works fine while the second does not. I am frustrated because I try everything that I see in forums with placing spaces in front or newline characters and nothing works.

Code in question:

// Get user input for the two dates:
printf("Enter Date #1 in format mm:dd:yyyy \n");
scanf("%i:%i:%i\n", &D1.month, &D1.day, &D1.year);

printf("Enter Date #2 in format mm:dd:yyyy\n");
scanf("%i:%i:%i", &D2.month, &D2.day, &D2.year);

I tried to put a space AND a newline character in there separatly and together, I tried to read in a dummy variable character to see if that would work. Why can I not enter any data in the second scanf??

The output is shown:

Enter Date #1 in format mm:dd:yyyy 
09:06:1995
Enter Date #2 in format mm:dd:yyyy
The number of days between 0:1529117256:94769206 and 9:6:1995 is -1783102426

I make a new post because I see explanations with characters but not with integers.

When you use %i with scanf :

scanf("%i",&inp);  //INPUT 09 AS MONTH OR ANYTHING

It will read input as octal due the prefixed 0 or leading zero when input is 09 , hence the value of inp becomes invalid since 9 is not a valid octal digit, octal digits being 0,1,2,3,4,5,6,7 .

Where as in case when %d is being used than 09 input will not be converted into octal and the value read will be 9 .

Apart from this there is something I would like to suggest: away-from-scanf

As given in comment (1) by user3121023 changin both to "%d" 's instead of "%i" 's fixed the issue. I am unclear why.

Code is now:

// Get user input for the two dates:
printf("Enter Date #1 in format mm:dd:yyyy \n");
scanf("%d:%d:%d", &D1.month, &D1.day, &D1.year);

printf("Enter Date #2 in format mm:dd:yyyy\n");
scanf("%d:%d:%d", &D2.month, &D2.day, &D2.year);

In addition:

"%d:%d:%d\n"

would not work. Do not put '\\n' in your scanf.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM