Loop for input validation ?

My program isn't working properly, when the input is not valid, it still executes the input ? Please help lol
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
  #include<iostream>
using namespace std;
int main()
{
	int positiveInteger;
    int startingNumber = 1;
	do
	{
    cout << "Please input a positive integer" << endl;

    cin >> positiveInteger;
    
	int result = 0; 
    for (int i=startingNumber; i <= positiveInteger; i++)
    {
        result += i;
        cout << result;
    }

    cout << result<<endl;
	}
	while(positiveInteger<=0);
    return 0;

}
closed account (EwCjE3v7)
You need to check if the value is positive, you can do this with an if statement

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
32
33
34
35
36
#include<iostream>
using namespace std;
int main()
{
	  #include<iostream>
using namespace std;
int main()
{
	int positiveInteger = -1; // its good to initialise your variables
    int startingNumber = 1;
	do
	{
    cout << "Please input a positive integer" << endl;
    
    cin >> positiveInteger;
    
    if (positiveInterger >= 0) { // check if value is positive
    	int result = 0; 
        for (int i=startingNumber; i <= positiveInteger; i++)
        {
            result += i;
            cout << result;
        }
    
        cout << result<<endl;
    	}
    	while(positiveInteger<=0);
	} else {
	    cout << "Invalid input, program terminating!" << endl;
	    return -1;
	}
    return 0;

}

}
Last edited on
it needs a loop to validate it... meaning if the input is invalid it returns to starting statement, not end the program.and why is positiveinteger = -1 ?
um.... help please anyone ?
=[
Last edited on
Nvm I figured it out on my own cause i'm smart like that =]
Topic archived. No new replies allowed.