Skip to Main Content
C Programming: Visual Quickstart Guide
book

C Programming: Visual Quickstart Guide

by Larry Ullman, Marc Liyanage
October 2004
Beginner content levelBeginner
408 pages
9h 24m
English
Peachpit Press
Content preview from C Programming: Visual Quickstart Guide

Reading Numeric Input

The previous two examples read in a single character and then an entire string. But what if you want to read in numeric input? For this, you can again use the scanf() function:

int age;
printf ("Enter your age: ");
scanf ("%d", &age);

This method generally works and has the added benefit of familiarity. Unfortunately, this function can be unreliable in properly handling numeric input (although it's still commonly used). A better solution—which is really a kludge (an inelegant solution)—uses the fgets() and sscanf() functions:

int age;
char input[10];
printf ("Enter your age: ");
fgets (input, sizeof(input)-1, stdin);
sscanf (input, "%d", &age)

With the fgets() function, the first argument (input) tells C to which variable ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Intermediate C Programming

Intermediate C Programming

Yung-Hsiang Lu
Data Structures Using C

Data Structures Using C

Samir Kumar Bandyopadhyay, Kashi Nath Dey

Publisher Resources

ISBN: 0321287630Purchase book