Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Basic input question 2

Status
Not open for further replies.

franklane

Programmer
Oct 5, 2004
12
0
0
US
Hi,

I'm curious about a behavior I observed. This is based on a question I attempted to answer in a different group.

Code snippet:

#include <iostream>
using namespace std;

int main () {
int i;

cout << "Input something: ";
cin >> i;

cout << "i=" << i << endl;

}//end main


If the user inputs the character L, i is displayed as zero. Why is it not 76? It seems like the input buffer would have to have the ASCII code for L in it and that that value would be fed to the program and appropriately promoted to the int data type with no loss of data. Obviously I don't understand what's happening here. Any clarification here would be greatly appreciated.

Thanks,
Frank
 
On my machine it outputs -858993460 or 4199248.

The reason is because cin cannot read 'L' as an int, and i is not initialized. If you initialized i when you declared it, then whatever you initialize it to will be displayed. This happens because cin >> i does not modify the contents of i if it fails to read in an integer. Since L is not an int, cin goes into a fail state and leaves the value of i alone.
 
After you input the 'L', do a cin.fail() and it should return true which means there was an error reading the integer. Then you'll need to call cin.clear() to set the state back to a good state before reading any more input with cin.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top