Problems when using scanf with %i to capture date (mm dd yyyy)

前端 未结 1 1567
一整个雨季
一整个雨季 2021-01-20 19:44

I\'m writing a program that calculates the number of elapsed days between two dates. To do this, I have to input the dates as integers in a structure defined like so:

<
相关标签:
1条回答
  • 2021-01-20 20:17

    Using the %i conversion specifier causes scanf() to parse the input as if strtol() was called with 0 as the base argument. So, since 08 begins with a 0, and 8 is not an x or X, it treats the 08 as an octal sequence. But, since 8 is not a valid octal number, it stops there, and the result is 0 for the first number.

    The second number then gets the 8, as it is delimited by whitespace. The white space is skipped, and the third number is parsing 08 as octal again, resulting in 0 for the third number. The remaining 8 and the year 2004 are not parsed.

    Use %d to parse decimal digits.

    scanf("%d %d %d", &startDate.month, &startDate.day, &startDate.year);
    

    As mentioned in the comments, scanf() should generally be avoided. As an alternative, you could use fgets() to retrieve an entire line of input first, and use sscanf() to do parsing. This allows for better error recovery, since an error can be diagnosed by the line that caused the error, and the line can be gracefully skipped as well. scanf() is meant for structured input, and can only give you a rough idea of where a scanning error occurred. And, errors cause the input to jam, leading to confusing debugging sessions at times.

    0 讨论(0)
提交回复
热议问题