Reputation: 21
#include<iostream>
using namespace std;
int main()
{
int x,y,n=0,ch='y';
while(ch=='y')//problem loop
{
gno:
x=rand()%9999+1000;
y=x;
n=0;
while(y>0)
{
y=y/10;
n++;
if(n>3&&n<3)
goto gno;
}
cout<<x<<endl;
cin>>ch;
}
return 0;
}
Whenever I run the above code, it displays one random number as it should. But after that even when I enter the value of ch as "y" (without the quotes, of course!) the while loop marked as "problem loop" just doesn't continue. Ya, I get it that it's some kind of a runtime error but can anyone please specify what is causing this problem, and by making what exact changes to the code will let me run it successfully?
Upvotes: 1
Views: 49
Reputation: 35540
You defined ch
as an int
, which means that cin
will interpret the input as an integer and read it into ch
. You can observe that this happens when you enter 121
and the code continues. To fix your issue, just change
int x,y,n=0,ch='y';
into
int x,y,n=0;
char ch='y';
Also, you have an if statement that will never happen, so you might as well get rid of the if(n>3&&n<3)
and the goto
. Keep in mind that goto is bad.
Upvotes: 3