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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

small problem with "cin"

Status
Not open for further replies.

hca

Programmer
Sep 25, 2000
5
US
I am in a c++ class and I am having a problem with part of my program. The code is as follows:
#include <iostream.h>
void main()
{
int num;
cout << &quot;Enter # of credits: &quot;;
cin >> num;

while(cin.fail()!=0)
{
cout << &quot;error&quot;;
cout << &quot;Enter # of credits: &quot;;
cin >> num;
}
}
Basically, I want to prompt the user to enter the number of credits, then test to see if the user entered an int. But if the user were to enter a letter, the program should report an error and re-prompt for # of credits. What happens is that when a user enters a non int value such as a letter, is the program goes into the while loops and &quot;error&quot; and &quot;Enter # of credits&quot; keeps getting displayed over and over, never stopping. And it doesnt let me re-enter the # of credits. Is the input buffer flooded? can I clear it out before I ask to re-enter the credits? I need this field to be and int so i can preform calculations with it later. Does anyone have any suggestions? [sig][/sig]
 
Hi,

U can read the user-inputs as following:

u declare the int as char, for example:

#include <iostream.h>

int main ( void )
{
char num[20];


cout << &quot;Enter # of credits: &quot;;
cin.getline ( num, sizeof ( num ));

etc.

return 0;
}

After that when u need the string as int u have to change it with the function &quot;atoi&quot;. For details look MSDN.

I hope this will help u ...

SiM [sig][/sig]
 
SiM

That is exactly what i was looking for. Thanks! [sig][/sig]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top