Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different types of input using template function

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?

like image 880
John Avatar asked Apr 22 '26 22:04

John


2 Answers

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);
}
like image 175
Zeppe Avatar answered Apr 25 '26 12:04

Zeppe


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()
}
like image 32
iammilind Avatar answered Apr 25 '26 11:04

iammilind