使用模板功能的不同类型的输入

时间:2011-09-17 06:49:36

标签: c++ templates input

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

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我不能。那么是否可以以类似于我正在做的方式输入多字符串以及基本类型?

4 个答案:

答案 0 :(得分:2)

我认为你还是想使用getline,因为你不想在每个提示后留下输入缓冲区中的东西。但是,要仅更改字符串的行为,可以使用模板特化。模板功能完成后:

template<>
void getInput(string prompt, string& inputVar)
{
    cout << prompt;
    getline(cin, inputVar);
}

答案 1 :(得分:2)

重载string的功能(或执行template专业化)。

void getInput(string prompt, string& inputVar) // <--- overloaded for 'string'
{
    cout << prompt;
    getline(cin, inputVar);  //<-- special treatment for 'string' using getline()
}

答案 2 :(得分:1)

我相信你需要特殊情况的字符串。 cin只会得到一个单词,您需要使用getline()来获取整行。请参阅this page以供参考。然后,您可以根据需要操纵该行:拆分,解析,等等。

不幸的是,这会破坏整条线路,如果你有类似"one two three 123 3.1415"的东西,那么整条线都会消耗掉。

另请参阅example here以获得更好的方法来决定数字/字符串/单词/浮点数。但这并没有充分利用模板。

答案 3 :(得分:0)

这样写的方式你可能会得到一些意想不到的结果。例如,您可以使用如下所示的会话:

String: Foo 12            3.14159  1.5 <enter>
Int: Float: Double: Foo 12 3.14159 1.5

我知道你刚才举了一个例子,但这几乎肯定不是你想做的。在按下enter之前,cin将永远不会注册任何输入,因此您可能希望使用getline逐行逐行。否则,事情会像上面那样变得时髦。

即使你有权访问每个按键,你可能也无法像你想要的那样完成内联。