To start with, your function is badly named and badly behaved.
- a function's name should clearly state what it does
- it should behave consistently
(Chervil's suggestion has solved the second part.)
But reverse engineering your code to extract the requirements, I would probably implement the required behaviour something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <string>
using namespace std;
bool getSpecificNumberFromUser(int numberWanted);
int main(){
int numberWanted = 1;
if( getSpecificNumberFromUser(numberWanted) )
cout << numberWanted << endl;
else
str = "You didn't enter " << numberWanted << endl;
return 0;
}
bool getSpecificNumberFromUser(int numberWanted){
int input = 0;
cout << "Enter a value: " << endl;
cin >> input;
return (input==numberWanted);
}
|
Also, as Peter87 has said, while it is not possible to change the return type of the function, it is possible to return a type that can represent (or store) multiple types. In addition to strings, you could also use a
variant, like the one in the Boost library:
Boost.Variant
http://www.boost.org/doc/libs/1_53_0/doc/html/variant.html
Using the variant with your original code, you get
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <string>
#include <boost/variant.hpp>
using namespace std;
using namespace boost;
variant< int, std::string > giveResults();
int main(){
cout << giveResults() << endl;
}
variant< int, std::string > giveResults(){
int input = 0;
cout << "Enter a value: " << endl;
cin >> input;
if(input==1){
return 1;
}else{
return "You didn't enter 1";
}
}
|
(But my above comments still hold; this is not a particularlly nice solution or use of Boost.Variant.)
Andy