How to ask a user to reenter an input.

Hi,

It is my second week already in my C++ plus and still getting a good grasp of C++

So as I was experimenting with my project, I came to a problem on how to ask the user to re-enter a positive number if a negative number was entered.

If "Invalid! Please..." phrase appears, I want the user to enter a

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
28
#include<iostream>
using namespace std;

int main()

{
	double number;
	cout << "Please enter a number: ";
	cin >> number;


	if (number > 0) 
	{
		cout << "You have entered a valid number." << endl;
		cout << "Thank you :)";

	}

	else 
	{
		cout << "Invalid! Please enter a postive number.";
	}

	cin >> number;

	fflush(stdin);
	cin.get();
}
hmm you could do it several ways, with a while/for loop or even a switch.

this is kinda sloppy and someone might scold me but i like using return 0; to terminate a program early.
anyways this is using a while(cin) loop.

there are many ways to achieve what you want though.

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
28
29
30
31
#include<iostream>
using namespace std;

int main()

{
	double number;
	cout << "Please enter a number: ";
	cin >> number;
	
	
while(cin)
{

	if (number > 0) 
	{
		cout << "You have entered a valid number." << endl;
		cout << "Thank you :)";
		return 0;

	}

	else 
	{
		cout << "Invalid! Please enter a postive number.";
	}

	cin >> number;
}
	return 0;
}
Last edited on
Topic archived. No new replies allowed.