1. Computing

Learn About Input and Output

By

7 of 8

Using cin For Input - Formatted Input
There are two types of input.
  • Formatted. Reading input as numbers or of a certain type.
  • Unformatted. Reading bytes or strings. This gives much greater control over the input stream.

Here is a simple example of formatted input.

 // excin_1.cpp : Defines the entry point for the console application.
 
 #include "stdafx.h" // Microsoft only
 #include <iostream>
 
 using namespace std;
 
 int main(int argc, char* argv[])
 {
 	int a = 0;
 	float b = 0.0;
 	int c = 0;
 	cout << "Please Enter an int, a float and int separated by spaces" <<endl;
 	cin >> a >> b >> c;
 	cout << "You entered " << a << " " << b << " " << c << endl;
 	return 0;
 }
 
This uses cin to read three numbers (int, float,int) separated by spaces. You must press enter after typing the number.

3 7.2 3 will output "You entered 3 7.2 3".

Formatted Input has Limitations!

If you enter 3.76 5 8, you get "You entered 3 0.76 5", all other values on that line are lost. That is behaving correctly, as the . is not part of the int and so marks the start of the float.

Error Trapping

The cin object sets a fail bit if the input was not successfully converted. This bit is part of ios and can be read by use of the fail() function on both cin and cout like this.
 if (cin.fail() ) // do something
 
Not surprisingly, cout.fail() is rarely set, at least on screen output. In a later lesson on file I/O, we'll see how cout.fail() can become true. There is also a good() function for cin, cout etc.

On the next page Error Trapping in Formatted Input

Related Video
Using Meta Data for Search
  1. About.com
  2. Computing
  3. C / C++ / C#
  4. C++ Programming
  5. Learn C++ Programming
  6. Using cin for Input

©2014 About.com. All rights reserved.