Dark
Dark

Reputation: 13

What does scanf("%d/%d/%d) mean in C?

int currD, currM, currY;
scanf("%d/%d/%d", &currD, &currM, &currY);

I saw this code receiving birth date in the format DD/MM/YYYY, but I wonder what's the meaning of putting '/', I know without this, it will lead to bad input because of the character '/'. So what does it actually mean?

Upvotes: 1

Views: 9745

Answers (5)

Konrad Rudolph
Konrad Rudolph

Reputation: 545568

When encountering code that you don’t understand, and which is calling a function from a library, your first order of business is to research the documentation for that function. For C standard functions it’s enough to google the function name.

A good reference in this case is cppreference (don’t be misled by the website name, this is the C reference, not the C++ reference). It gives the function’s definition as

int scanf( const char *format, ... );​

Now look for the parameter description of the format parameter:

pointer to a null-terminated character string specifying how to read the input.

The subsequent text explains how to read the format string. In particular:

  • […] character [except %] in the format string consumes exactly one identical character from the input stream, or causes the function to fail if the next character on the stream does not compare equal.
  • conversion specifications [in] the following format
    • introductory % character
    • conversion format specifier
    • d — matches a decimal integer.

In other words:

scanf parses a textual input based on the format string. Inside the format string, / matches a slash in the user input literally. %d matches a decimal integer.

Therefore, scanf("%d/%d/%d", …) will match a string consisting of three integers separated by slashes, and store the number values inside the pointed-to variables.

Upvotes: 1

Mayhem
Mayhem

Reputation: 507

It expects the input to be in the format three integers separated by two slashes ("/"). For example: 10/11/1999.

Upvotes: 0

Arulpandiyan Vadivel
Arulpandiyan Vadivel

Reputation: 417

Input is expected to provide like 04/07/2019. If input is provided only 04072019. currD alone hold the value 04072019, currM and currY might garbage value as it is not initialised.

Upvotes: 0

Dali
Dali

Reputation: 344

The first parameter of scanf is a string specifying the format of the string you want to use to store the informations in the further arguments. You can see this format string as a pattern : %d means an integer, and without the '%' it means it just has to match exactly the characters.

Upvotes: 0

AlanWik
AlanWik

Reputation: 322

Is just the separator in the date format. The error must raise when some function searchs for those /.

Upvotes: 0

Related Questions