I'm try to get input from a user using a templated function. I want to be able to input int, doubles, floats, and strings. So here's the code I have so far:
template<class DataType>
void getInput(string prompt, DataType& inputVar)
{
cout << prompt;
cin >> inputVar;
}
int main()
{
string s;
int i;
float f;
double d;
getInput("String: ", s);
getInput("Int: ", i);
getInput("Float: ", f);
getInput("Double: ", d);
cout << s << ' ' << i << ' ' << f << ' ' << d << endl;
return 0;
}
The basic types all work, but the problem I have lies with inputting strings. I'd like to be able to input more than one word, but to the fact that I'm using cin I can't. So is it possible input multi-word strings as well the basic types in a manner similar to what I'm doing?
I think you want to use getline anyway, as you don't want to leave stuff in your input buffer after each prompt. To change the behaviour only for strings, though, you can use a template specialisation. After your template function:
template<>
void getInput(string prompt, string& inputVar)
{
cout << prompt;
getline(cin, inputVar);
}
Overload the function for string (or do template specialization).
void getInput(string prompt, string& inputVar) // <--- overloaded for 'string'
{
cout << prompt;
getline(cin, inputVar); //<-- special treatment for 'string' using getline()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With