使用模板函数的不同类型的输入

2024-02-21

我尝试使用模板函数从用户那里获取输入。我希望能够输入 int、double、float 和 strings。这是我到目前为止的代码:

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;
}

基本类型都可以工作,但我遇到的问题在于输入strings。我希望能够输入多个单词,但由于我使用的是 cin,所以我不能。那么是否可以以类似于我正在做的方式输入多字字符串以及基本类型?


我认为无论如何你都想使用 getline,因为你不想在每次提示后在输入缓冲区中留下东西。不过,要仅更改字符串的行为,您可以使用模板专业化。在你的模板函数之后:

template<>
void getInput(string prompt, string& inputVar)
{
    cout << prompt;
    getline(cin, inputVar);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用模板函数的不同类型的输入 的相关文章