3.6 Input
The standard library offers istreams for input. Like ostreams, istreams deal with character string representations of built-in types and can easily be extended to cope with user-defined types.
The operator >> (''get from'') is used as an input operator; cin is the standard input stream. The type of the right-hand operand of >> determines what input is accepted and what is the target of the input operation. For example,
void f() { int i; cin >> i; // read an integer into i double d; cin >> d; // read a double-precision, floating-point number into d }
reads a number, such as 1234, from the standard input into the integer variable i and a floating-point number, such as 12.34e5, into the double-precision, floating-point variable d.
Here is an example that performs inch-to-centimeter and centimeter-to-inch conversions. You input a number followed by a character indicating the unit: centimeters or inches. The program then outputs the corresponding value in the other unit:
int main() { const float factor = 2.54; // 1 inch equals 2.54 cm float x, in, cm; char ch = 0; cout << "enter length: "; cin >> x; // read a floating-point number cin >> ch; // read a suffix switch (ch) { case 'i': // inch in = x; cm = x*factor; break; case 'c': // cm in = x/factor; cm = x; break; default: in = cm = 0; break; } cout << in << " in = " << cm << " cm\n"; }
The switch-statement tests a value against a set of constants. The break-statements are used to exit the switch-statement. The case constants must be distinct. If the value tested does not match any of them, the default is chosen. The programmer need not provide a default.
Often, we want to read a sequence of characters. A convenient way of doing that is to read into a string. For example:
int main() { string str; cout << "Please enter your name\n"; cin >> str; cout << "Hello, " << str << "!\n"; }
If you type in
Eric
the response is
Hello, Eric!
By default, a whitespace character such as a space terminates the read, so if you enter
Eric Bloodaxe
pretending to be the ill-fated king of York, the response is still
Hello, Eric!
You can read a whole line using the getline() function. For example:
int main() { string str; cout << "Please enter your name\n"; getline(cin,str) ; cout << "Hello, " << str << "!\n"; }
With this program, the input
Eric Bloodaxe
yields the desired output:
Hello, Eric Bloodaxe!
The standard strings have the nice property of expanding to hold what you put in them, so if you enter a couple of megabytes of semicolons, the program will echo pages of semicolons back at youunless your machine or operating system runs out of some critical resource first.