1. Home
  2. Computing & Technology
  3. C / C++ / C#

Learn About Input and Output

By David Bolton, About.com

8 of 8

Error Trapping in Formatted Input

Here is an example of input looping until a floating point number has been correctly entered.
// excin_2.cpp

#include "stdafx.h" // Microsoft only
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
float floatnum;
cout << "Enter a floating point number:" <<endl;
while(!(cin >> floatnum))
{
cin.clear() ;
cin.ignore(256,'\n') ;
cout << "Bad Input - Try again" << endl;
}
cout << "You entered " << floatnum << endl;
return 0;
}
This example requests a float number and only exits when it has one. If it cannot convert the input, it outputs an error message and calls clear() to clear the fail bit. The ignore function skips all the rest of the input line. 256 is a sufficiently large number of characters that the \n will be reached before all 256 have been read.

Note: An input such as 654.56Y will read all the way up to the Y, extract 654.56 and exit the loop. It is considered valid input by cin

Unformatted Input

This is a more powerful way of inputting characters or entire lines, rather than keyboard input but that will be left for a later lesson on file I/O.

Keyboard Entry

All the input, using cin requires the Enter or Return key to be pressed. Standard C++ does not provide a way to read characters directly from a keyboard. In future lessons we'll see how to do that with third party libraries.

This ends the lesson.

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Error Trapping in Formatted Input

©2009 About.com, a part of The New York Times Company.

All rights reserved.