- 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.This uses cin to read three numbers (int, float,int) separated by spaces. You must press enter after typing the number.
#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;
}
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 somethingNot 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

