使用模板功能的不同类型的输入 [英] Different types of input using template function
问题描述
我正在尝试使用模板化功能从用户那里获取输入.我希望能够输入int,double,float和string.所以这是我到目前为止的代码:
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;
}
所有基本类型都可以使用,但是我遇到的问题在于输入string
s.我希望能够输入多个单词,但是事实上,我使用的是cin,但我却不能.那么是否可以以与我正在执行的方式类似的方式输入多字字符串以及基本类型?
The basic types all work, but the problem I have lies with inputting string
s. 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?
推荐答案
重载string
的功能(或进行template
专门化).
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()
}
这篇关于使用模板功能的不同类型的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!