FAQ 2.13 What are the basics of stream input?

graphics/new_icon.gif

C++ supports C-style input, such as the scanf() family of functions. However it is often better to use the native C++ input services. With the native C++ input services, information is read from an input stream object. For example, cin is an input stream object that is attached to the process's standard input device, often to the keyboard from which the program is run. Syntactically these C++ input services look as if they're shifting things from the input stream object. The <iostream> header is needed when using these services (the example uses stream output to prompt for the stream input):

 #include <iostream> #include <string> using namespace std; int main() {   cout << "What's your first name? ";                <-- 1   string name;                                       <-- 2   cin >> name;                                       <-- 3   cout << "Hi " << name << ", how old are you? ";   int age;   cin >> age;                                        <-- 4 } 

(1) Line 1

(2) Line 2

(3) Line 3

(4) Line 4

Line 1 prints the prompt. There is no need to flush the stream since cout takes care of that automatically when reading from cin (see the tie member function in the iostream documentation for how to do this with any arbitrary pair of streams).

Line 2 creates a string object called name. Class string is a standard class that replaces arrays of characters. string objects are safe, flexible, and high performance. This line also illustrates how C++ variables can be defined in the middle of the routine, which is a minor improvement over the C requirement that variables be defined at the beginning of the block.

Line 3 reads the user's first name from the standard input and stores the result in the string object called name. This line skips leading whitespace (spaces, tabs, newlines, and so on), then extracts and stores the whitespace-terminated word that follows into variable name. The analogous syntax in C would be fscanf(stdin, "%s", name), except the C++ version is safer (the C++ string object automatically expands its storage to accommodate as many characters as the user types in there is no arbitrary limit and there is no danger of a memory overrun). Note that an entire line of input can be read using the syntax getline(cin, name);.

Line 4 reads an integer from the standard input and stores the result in the int object called age. The analogous syntax in C would be fscanf(stdin, "%d", &age), except the C++ version is simpler (there is no redundant "%d" format specifier since the C++ compiler knows that age is of type int, and there is no redundant address-of operator (&age) since the compiler passes the parameter age by reference).



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net