C scanf behaves unexpectedly with% i to scan dates

For some reason, when I run my program, it does not allow me to enter numbers for the operators associated with day1 and year2. Why is he doing this?

#include <stdio.h> int main(void ) { int day1, day2, month1, month2, year1, year2; printf("Enter date 1 mm\n"); scanf("%i", &month1); printf("Enter date 1 dd\n"); scanf("%i", &day1); printf("Enter date 1 yyyy\n"); scanf("%i", &year1); printf("Enter date 2 mm\n"); scanf("%i", &month2); printf("Enter date 2 dd\n"); scanf("%i", &day2); printf("Enter date 2 yyyy\n"); scanf("%i", &year2); return 0; } 
+6
source share
2 answers

Are you printing 08 or 09 for the first mm value?

If so, then the problem is: the %i conversion specification takes 0x before the hexadecimal value and 0 to the octal value (see the POSIX specification for scanf() ). If you type 08 or 09 , then only the zero value will be equal to octal, so it leaves 8 or 9 at the input, which is immediately read as the value of day1 . Similarly, you will probably enter 08 or 09 for day2 , and the same failure will occur, so day2 contains 0 and year2 contains 8 or 9.

You can help yourself and everyone else:

  • Checking success of calls to scanf() .
  • Print values ​​entered from the program.
  • Inclusion of a transcript of an executable program.

For instance:

 #include <stdio.h> int main(void ) { int day1, day2, month1, month2, year1, year2; printf("Enter date 1 mm\n"); scanf("%i", &month1); printf("Enter date 1 dd\n"); scanf("%i", &day1); printf("Enter date 1 yyyy\n"); scanf("%i", &year1); printf("Enter date 2 mm\n"); scanf("%i", &month2); printf("Enter date 2 dd\n"); scanf("%i", &day2); printf("Enter date 2 yyyy\n"); scanf("%i", &year2); printf("%.4d-%.2d-%.2d to %.4d-%.2d-%.2d\n", year1, month1, day1, year2, month2, day2); return 0; } 

Run Example:

 $ ./date1 Enter date 1 mm 08 Enter date 1 dd Enter date 1 yyyy 1999 Enter date 2 mm 12 Enter date 2 dd 09 Enter date 2 yyyy 1999-00-08 to 0009-12-00 $ 

The code does not check scanf() calls, but it illustrates the behavior you saw.

Fix

If you want numbers to be decimal even with leading zeros, use %d instead of %i .

Only the toughest C programmers enter dates in octal or hexadecimal.

+12
source

You need %d to take int as d numeric characters.

 scanf("%d", &year2); 
-3
source

Source: https://habr.com/ru/post/984674/


All Articles