2011-09-17 29 views
3

我试图从使用模板函数的用户获取输入。我希望能够输入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我不行。那么是否有可能以类似于我正在做的方式输入多字符串以及基本类型?

+0

使用cin.getline()然后你可以拆分程序中的单词 –

+0

但是,那么我会失去输入整数,浮点数和双精度的能力是否正确? – John

+0

看到我的答案,第二个链接可能是有用的。 – evgeny

回答

1

我相信你会需要特殊字符串。 cin只会得到一个单词,并且您需要使用getline()获得整行。请参阅this page以供参考。然后,您可以按照您认为合适的方式操作该行:分割它,解析它,不是。

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

另请参阅example here以更好地确定数字/字符串/词/浮点数。但是这并没有充分利用模板。

2

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

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

删除我的答案,赞成这一个。 – Johnsyweb

+0

这个技巧。现在,C++如何处理模板特化与函数重载有什么区别? – John

+0

@John:http://www.gotw.ca/gotw/049.htm – Johnsyweb

2

超载为string函数(或做template专业化)。

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

这是写的方式,你可能会得到一些可能意想不到的结果。例如,你可以有一个是这样的一个会话:

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

我知道你刚才举了一个例子,但是这是几乎可以肯定不是你想要做什么。 cin将永远不会注册任何输入,直到输入被按下,所以你可能想要使用getline一行一行。否则,事情会变得像上面那样时髦。

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

相关问题