UMBC CS 201, Spring 02
UMBC CMSC 201 Spring '02 CSEE | 201 | 201 S'02 | lectures | news | help

scanf5

Our last example shows that scanf tries to match items in the input stream.

In this program, we want the user to enter a date with dashes separating the month, day and year values.

scanf will try to match the dashes. If the dashes don't exist in the input, the remainder of the values to be scanned will be ignored.

The Program

/********************************************* ** File: scanf5.c ** Author: SAB ** Date: 2/2/97 ** Section: 101 ** SSN: 123-45-6789 ** EMail: bogar@cs.umbc.edu ** ** This program shows scanf trying to match ** specific characters in the input. ** **********************************************/ #include <stdio.h> int main ( ) { int month, day, year, numRead; printf("Enter the date using this format:\n"); printf("##-##-##"\n); numRead = scanf("%d-%d-%d", &month, &day, &year); printf("You entered %02d-%02d-%02d\n", month, day, year); printf("The number of items read was %d\n", numRead); return 0; }

The Sample Run

linux3[103] % a.out Enter the date using this format: ##-##-## 9-5-99 You entered 09-05-99 The number of items read was 3 linux3[104] % linux3[104] % !a a.out Enter the date using this format: ##-##-## 09-05-99 You entered 09-05-99 The number of items read was 3 linux3[105] % !a a.out Enter the date using this format: ##-##-## 9-5-1999 You entered 09-05-1999 The number of items read was 3 linux3[106] % !a a.out Enter the date using this format: ##-##-## 9/5/1999 You entered 09-134518160-134513643 The number of items read was 1 linux3[107] %


CSEE | 201 | 201 S'02 | lectures | news | help

Thursday, 17-Jan-2002 13:52:24 EST