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

scanf3

Our third example shows that scanf can be used to read in several integers per line.

The value returned by scanf is actually the number of variables successfully read.

If scanf encounters the end-of-file character (control-D on UNIX), then it returns a -1.

The Program

/******************************************** ** File: scanf3.c ** Author: S Bogar ** Date: 2/2/97 ** Section: 101 ** SSN: 123-45-6789 ** EMail: bogar@cs.umbc.edu ** ** This program shows the return values ** given by scanf. ** **********************************************/ #include <stdio.h> int main ( ) { int n1, n2, n3, numRead ; printf("Enter three integers: ") ; numRead = scanf("%d%d%d", &n1, &n2, &n3) ; printf("n1 = %d, n2 = %d, n3 = %d, numRead = %d\n", n1, n2, n3, numRead) ; return 0; }

The Sample Run

linux3[91] % gcc -Wall -ansi scanf3.c linux3[92] % a.out Enter three integers: 123 456 789 n1 = 123, n2 = 456, n3 = 789, numRead = 3 linux3[93] % linux3[93] % a.out Enter three integers: 123 456 aaa n1 = 123, n2 = 456, n3 = 134513643, numRead = 2 linux3[94] % linux3[94] % !a a.out Enter three integers: 123 aaa 789 n1 = 123, n2 = 134518072, n3 = 134513643, numRead = 1 linux3[95] % linux3[95] % !a a.out Enter three integers: abc n1 = 134518092, n2 = 134518072, n3 = 134513643, numRead = 0 linux3[96] % linux3[96] % !a a.out Enter three integers: ^D n1 = 134518092, n2 = 134518072, n3 = 134513643, numRead = -1 linux3[97] %


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

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