我试图从使用模板函数的用户获取输入。我希望能够输入int,双精度,浮点数和字符串。因此,这里的代码,我到目前为止:使用模板函数的不同类型的输入
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
秒。我希望能够输入多个单词,但是要使用cin我不行。那么是否有可能以类似于我正在做的方式输入多字符串以及基本类型?
使用cin.getline()然后你可以拆分程序中的单词 –
但是,那么我会失去输入整数,浮点数和双精度的能力是否正确? – John
看到我的答案,第二个链接可能是有用的。 – evgeny