Another problem is that your funcInputFormation() function doesn't return the number that was entered.
However, when dealing with user input in C++ using streams, it is almost always best to read the input as a string and convert it to integral format. The reason being that mikeb's example code goes into an infinite loop if the user enters anything other than a number.
Here is how I'd implement funcInputFormation():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
int funcInputFormation() {
// Exit loop if standard input is closed (CTRL-D, or EOF if redirected)
while( cin ) {
string answer;
cout << "Enter a number between 1 and 20: " << flush;
cin >> answer;
// Sorry, I'm going to use an advanced way to convert the number
// to make the example shorter.
try {
int result = boost::lexical_cast<int>( answer );
if( result < 1 || result > 20 )
cerr << "Invalid number entered. Try again." << endl;
else
return result;
} catch( ... ) {
// If the input was not integral, output error and try again.
cerr << "Invalid input. Try again." << endl;
}
cerr << "End of input reached!" << endl;
exit( 0 ); // Just exit program I guess....
}
|
boost::lexical_cast<> is a convenient way to convert strings to integers, however you can also use functions like strtod, strtol, and atoi (though atoi can't tell you if the conversion failed, so I'd use strtod).
Lastly, in your main program, you need to capture the return code from funcInputFormation():
1 2
|
int answer = funcInputFormation();
// Now use answer for whatever you need it for...
|
[Edit: and forget about the try {} catch {} syntax too... that is how you detect if boost::lexical_cast<> failed to convert the number.]