| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Help with loop
Code:
#include <iostream.h>
#include "G:\Adv Prog\C++ files\lvp\String.h"
void main()
{
int again=0;
do
{
int num=0;
cout<<"Enter num: ";
cin>>num;
if(num==1)
{
cout<<"one";
again=0;
}
else if(num==2)
{
cout<<"two";
again=0;
}
else
{
num=0;
again=1;
}
}while(again==1);
cout<<"\nDONE\n";
}
I'm trying to figure out how to polish my code up so that if you enter a 'g' it will loop to the top and allow you to re-enter a number. If you enter any integer other than 1 or 2 it will work perfectly and loop to the top. If you enter anything other than an integer it will keep looping and won't let you input another integer. How do I get it so that it loops to the top when anything other than an integer is entered?? Thanks~ |
|
#2
|
|||
|
|||
|
a couple things generally:
-what is the String.h for? not needed in this program -<*.h> is the old deprecated format for standard headers, use <*> instead and put using namespace std; after the #include line -main must return int, and you should put return 0 at the end Now on to your question. You ask cin to expect an int, so when it gets a character it goes into the fail state. Then the next input does nothing, so you go into an endless loop. To fix this, add this code before the cin>>num line: Code:
if (!cin) //test for failure state
{
cin.clear(); //clear failure state
char c = '\0';
cin >> c; //get the character that was input
if (c == 'g') num = -1;
}
//then add another if statement after the input
if (num == -1)
{
cout << "gee";
again = 0;
}
This makes it so any character besides g will also cause termination, while g will trigger continuation. |
|
#3
|
|||
|
|||
|
Quote:
Thanks bro ^^ |
|
#4
|
|||
|
|||
|
Code:
int main()
{
int again =0;
int num=0;
do{
cout<<"Enter number: ";
cin>>num;
switch(num)
{
case 1 :
cout<<"one<<endl;
again = 0;
break;
case 2:
cout<<"two"<<endl;
again = 0;
break;
default:
num=0
again = 1;
}
}while(again ==1);
cout<<"done"<<endl;
return 0;
}
|
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Help with loop |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|