#include <iostream>
#include <limits>
usingnamespace std;
int convert(int &input);
int main()
{
int input;
cout << "input a number [1/100]" <<endl;
cout<< "your number is " << convert(input);
return 0;
}
int convert(int &input)
{
bool valid = false;
while (!valid)
{
if(cin >> input)
{
//this checks whether an integer was entered
if(input <= 100 && input > 0)
valid = true;//then we have to see if this integer is in range
}
else
cin.clear(); //some cleaning up
cin.ignore(numeric_limits < streamsize > ::max(), '\n');//empty input stream
if(!valid)
cout << "this input is not valid\n";
}
return input;
}
if i wanted to ask the user to input a number from 1 to 10 again using the same function how would i change the lines of 26 to suit my needs?
how do i make line 22 not use cout???
in main comments test 1 show that that it works like i intended, but comment test 2 does do what i wanted it to, but i dont know why i have to use cout to use that function? is there a better way to adjust this to make this code more readable (meaning the function was intended in test 1 to display and test 2 was intended to grab the users input )???
the function's sole purpose is to stop the users input from being out of the specified range(which changes) and characters
#include <iostream>
#include <limits>
usingnamespace std;
int max_num_select(int &input, int &max);
int main()
{
int input, max; // values for function max_num_select() // use variable input for menu selction to cin
//test 1
cout << "input a number [1/100]" <<endl;
cout<< "your number is " << max_num_select(input, max = 100) <<endl;
cout << "input a number [1/10]" <<endl;
cout << "your number is " << max_num_select(input, max = 10) <<endl;
//test 2
cout << "1) play" <<endl;
cout << "2) options" <<endl;
cout << "3) character" <<endl;
cout << max_num_select(input, max = 3)<<"\r"; // \r only when not displaying user's input to delete function displaying it
if(input == 1) cout << "playing";
if(input == 2) cout << "options menu";
if(input == 3) cout << "character menu";
return 0;
}
int max_num_select(int &input, int &max)//function to stop user entering character or value out of range
{
bool valid = false;
while (!valid)
{
if(cin >> input)
{
//this checks whether an integer was entered
if(input <= max && input > 0)
valid = true;//then we have to see if this integer is in range
}
else
cin.clear(); //some cleaning up
cin.ignore(numeric_limits < streamsize > ::max(), '\n');//empty input stream
if(!valid)
cout << "that input is not valid\n";
}
return input;
}