C Programming: Keyboard Input
C Programming: Keyboard Input
printf("Type in a number \n"); scanf("%d", &number); printf("The number you typed was %d\n", number); } SampleProgramOutput Type in a number 23 The number you typed was 23
Anintegercallednumberisdefined.Aprompttoenterinanumberisthenprintedusingthestatement
printf("Type in a number \n:");
pdfcrowd.com
Thescanfroutine,whichacceptstheresponse,hastwoarguments.Thefirst("%d")specifieswhattypeofdatatype isexpected(iechar,int,orfloat).Listofformattersforscanf()foundhere. Thesecondargument(&number)specifiesthevariableintowhichthetypedresponsewillbeplaced.Inthiscasethe responsewillbeplacedintothememorylocationassociatedwiththevariablenumber. Thisexplainsthespecialsignificanceofthe&character(whichmeanstheaddressof). Sample program illustrating use of scanf() to read integers, characters and floats
#include < stdio.h > main() { int sum; char letter; float money; printf("Please enter an integer value "); scanf("%d", &sum ); printf("Please enter a character "); /* the leading space before the %c ignores space characters in the input */ scanf(" %c", &letter ); printf("Please enter a float variable "); scanf("%f", &money ); printf("\nThe printf("value printf("value printf("value }
open in browser PRO version
Are you a developer? Try out the HTML to PDF API
variables you entered were\n"); of sum = %d\n", sum ); of letter = %c\n", letter ); of money = %f\n", money );
pdfcrowd.com
SampleProgramOutput Please enter an integer value 34 Please enter a character W Please enter a float variable 32.3 The variables you entered were value of sum = 34 value of letter = W value of money = 32.300000
This program illustrates several important points. theclanguageprovidesnoerrorcheckingforuserinput.Theuserisexpectedtoenterthecorrectdatatype. Forinstance,ifauserenteredacharacterwhenanintegervaluewasexpected,theprogrammayenteran infinitelooporabortabnormally. itsuptotheprogrammertovalidatedataforcorrecttypeandrangeofvalues. CopyrightBBrown.1984-1999.Allrightsreserved.
pdfcrowd.com