1 <!DOCTYPE HTML PUBLIC
"-//W3O//DTD W3 HTML 2.0//EN">
2 <!-- This collection of hypertext pages is Copyright 1995-7 by Steve Summit. -->
3 <!-- This material may be freely redistributed and used -->
4 <!-- but may not be republished or sold without permission. -->
7 <link rev=
"owner" href=
"mailto:scs@eskimo.com">
8 <link rev=
"made" href=
"mailto:scs@eskimo.com">
9 <title>6.4 Reading Numbers
</title>
10 <link href=
"sx6c.html" rev=precedes
>
11 <link href=
"sx7.html" rel=precedes
>
12 <link href=
"sx6.html" rev=subdocument
>
15 <H2>6.4 Reading Numbers
</H2>
17 <p>The
<TT>getline
</TT> function of the previous section
21 What if we want to read a number?
22 One straightforward way is to read a string as before,
23 and then immediately convert the string to a number.
24 The standard C library contains a number of functions for doing this.
25 The simplest to use are
26 <TT>atoi()
</TT>, which converts a string to an integer, and
27 <TT>atof()
</TT>, which converts a string to a floating-point number.
28 (Both of these functions are declared in the header
<TT><stdlib.h
></TT>,
29 so you should
<TT>#include
</TT> that header
30 at the top of any file using these functions.)
31 You could read an integer from the user like this:
33 #include
<stdlib.h
>
37 printf(
"Type an integer:\n");
41 Now the variable
<TT>n
</TT> contains the number typed by the user.
42 (This assumes that the user
<em>did
</em> type a valid number,
43 and that
<TT>getline
</TT> did not return
<TT>EOF
</TT>.)
44 </p><p>Reading a floating-point number is similar:
46 #include
<stdlib.h
>
50 printf(
"Type a floating-point number:\n");
54 (
<TT>atof
</TT> is actually declared as returning type
<TT>double
</TT>,
55 but you could also use it with a variable of type
<TT>float
</TT>,
58 C automatically converts between
<TT>float
</TT> and
59 <TT>double
</TT> as needed.)
60 </p><p>Another way of reading in numbers,
61 which you're likely to see in other books on C,
62 involves the
<TT>scanf
</TT> function,
65 so we won't discuss it for now.
66 (Superficially,
<TT>scanf
</TT> seems simple enough,
67 which is why it's often used,
68 especially in textbooks.
69 The trouble is that to perform input reliably using
<TT>scanf
</TT>
70 is not nearly as easy as it looks,
71 especially when you're not sure what the user is going to type.)
75 <a href=
"sx6c.html" rev=precedes
>prev
</a>
76 <a href=
"sx7.html" rel=precedes
>next
</a>
77 <a href=
"sx6.html" rev=subdocument
>up
</a>
78 <a href=
"top.html">top
</a>
81 This page by
<a href=
"http://www.eskimo.com/~scs/">Steve Summit
</a>
82 //
<a href=
"copyright.html">Copyright
</a> 1995-
1997
83 //
<a href=
"mailto:scs@eskimo.com">mail feedback
</a>