Writing code


how do I write that the user can input any number between 0 and 360?
I am using microsoft visual 2010
Last edited on
first of all, i'm suggesting and i'm trying not to be a smart*ss, don't think "how to write it?" instead "how the logic/concept is?"
Something like this:

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>

int main()
{
    const int minv = 0 ;
    const int maxv = 360 ;

    int number ;
    
    while(true)
    {
        std::cout << "please enter a number in [" << minv << ',' << maxv << "]: " ;

        // if the user has entered a valid number, there is nothing more to be done
        if( std::cin >> number && number >= minv && number <= maxv ) break ;

        // else
        std::cin.clear() ; // clear the error state
        // http://www.cplusplus.com/reference/ios/ios/clear/

        std::cin.ignore( 1000, '\n' ) ; // discard invalid input
        // http://www.cplusplus.com/reference/istream/istream/ignore/

        // and try again
    }

    std::cout << "you entered " << number << '\n' ;
}
Well here's a very simple way to do that:

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 number;
	cout<<"Please enter a number (0 - 360): " <<endl;
	cin>>number;

	if ( number > 360 )
	{
		do
		{
			cout<<"Please enter a number between 0 - 360 (no higher): " <<endl;
			cin>>number;
		}while ( number > 360 ); //keeps looping as long as the number is higher than 360
	}
	else if ( number < 0 )
	{
		do
		{
			cout<<"Please etner a number between 0 - 360 (no lower): " <<endl;
			cin>>number;
		}while ( number < 0 );//keeps looping as long as the number is Lower than 0
	}
	return 0;
}


or like this if you happen to be a while loop fan:

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

int main()
{
	int number;
	cout<<"Please enter a number (0 - 360): " <<endl;
	cin>>number;

	while ( number > 360 )
	{
		cout<<"Please enter a number between 0 - 360 (no higer): " <<endl;
		cin>>number;
	}
	while ( number < 0 )
	{
		cout<<"Please enter a number between 0 - 360 (no lower): " <<endl;
		cin>>number;
	}
return 0;
}
Last edited on
closed account (N36fSL3A)
Where are your new line characters?
The two previous answers will allow you to enter a number outside 0-360 (enter -1 first then 361).... try this:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int main()
{
	int number;
	do {
		cout << "Please enter a number (0 - 360): " << endl;
		cin >> number;
	} while (number < 0 || number > 360);
	return 0;
}
Great example @JLBorges ;D
Topic archived. No new replies allowed.