Search code examples
cscanfquotes

Using messages inside format control string


When using the scanf function, I've been using a format string like scanf("%d",&x);. However, I'm curious about something for few days ago, so I'm asking a question.

What happens when you put a character in the quotation marks of the scanf function?

Example:

printf("Please enter the date you were born: ex.1999/5/6 : ")
scanf("%d/%d/%d", &year, &month, &date);

Solution

  • scanf reads a data stream from stdin and tries to parse your format string. If it doesn't fit, it stops processing. It is important to understand that the rest of the input remains in stdin stream for subsequent reads. scanf returns the number of values that have successfully been parsed.

    From my experience it is best to write a small program and test the behavior by yourself:

    #include "stdio.h"
    
    void main() {
            int year = 0;
            int month = 0;
            int date = 0;
            int count;
    
            while (1) {
                    printf("enter data:\n");
                    count = scanf("%d/%d/%d", &year, &month, &date);
                    printf("data received:\n");
                    printf("%d-%d-%d count=%d\n", year, month, date, count);
            }
    }
    

    Example 1: Fresh start and enter correct data:

    enter data:
    1/2/3
    data received:
    1-2-3 count=3
    

    Example 2: Fresh start and enter wrong data:

    enter data:
    1 2 3
    data received:
    1-0-0 count=1
    enter data:
    data received:
    2-0-0 count=1
    enter data:
    data received:
    3-0-0 count=1
    

    You can see that scanf reads the data only until the space after 1 because it doesn't fit the format string. scanf only changes the value of the first variable. Still the rest of your input, which is 2 3, is in stdin. The loop continues and the next call to scanf reads the 2. The space in front of the number is skipped. This happens without any user interaction! Again no slash is found. And so on. Try it yourself with different cases and understand that using scanf is a dangerous thing ... and if you don't initialise the variables and parsing fails you will get uninitialised data!