A program that asks for a number and until correct number is inputed keeps asking

I'm writing a program that asks for a number and until that number is 99 it keeps asking the user to enter another number... I have this code and it runs but I'm having trouble getting it to accept the answer 99 if it is guessed and to stop the program from running. It's in C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
1 #include<iostream>
2 using namespace std;
3 
4 int main()
5 {
6 int i=99;
7 int n;
8 
9 cout <<" Please enter a number" << endl;
10 cin >> n;
11 
12 
13 while (n!=i);
14 {
15 cout <<" enter another number" << endl;
16 cin >> n;
17 if (n==i){
18 
19 cout << "correct number" << endl;
20 }
21 }
22 
23 }
This should point you in the right direction and show you what errors you made so far. This is just a working version, not an ideal version -- there's still plenty of room for improvement. If you have more questions, feel free to ask.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>
using namespace std;

int main()
{
	int i=99;
	int n;

	cout <<" Please enter a number" << endl;
	cin >> n;


	while (n!=i); // This ; was messing things up and making the while loop just run infinitely without doing anything.
	{
		cout <<" enter another number" << endl;
		cin >> n;
		if (n==i) // If we exit the loop, the number must be correct anyway; no need to check here.
		{
			cout << "correct number" << endl;
		}
	}

	cout << "correct number" << endl; // We exited the loop, so i must be equal to n

	return 0; //Main is declared as int main() so it must return an integer.

}
Last edited on
insert the break command after the statement n==i

1
2
3
4
if(n==i){
cout<<"Correct Number"<<endl;
break; //causes the compiler to insert a jump statement to exit the loop 
}
Last edited on
Thanks! got it running perfectly!
Topic archived. No new replies allowed.