2014-11-21 58 views
0

我想接受程序的一些输入,输入是整数值。 接受输入的条件是输入数量不固定 但是要输入的最大输入数量是固定的。例如, 可以说最大输入限制是15个输入。 所以我应该能够接受“n”个输入,其中“n”可以有1到15之间的任何值。 有没有办法在cpp中做到这一点?接受随机数的输入cpp

+0

此链接可能是相关的http://stackoverflow.com/questions/1657883/variable-number-of-arguments-in-c – rhodysurf 2014-11-21 17:03:36

+0

您是否正在寻找可变数量的控制台应用程序的参数?或者函数调用的可变数量的参数。两者都可以完成。 – sfjac 2014-11-21 17:06:13

+0

@sfjac函数调用的可变参数个数 – Anuj 2014-11-21 17:08:54

回答

0

在C和C++中有一个用于编写接受任意数量参数的函数的通用机制。 Variable number of arguments in C++?。但是,这不会限制参数的数量或将过载限制为固定类型,并且使用(IMO)通常有点笨重。

它可以做一些与可变参数模板,例如:

#include <iostream> 
#include <vector> 

using namespace std; 


void vfoo(const std::vector<int> &ints) 
{ 
    // Do something with the ints... 
    for (auto i : ints) cout << i << " "; 
    cout << endl; 
} 


template <typename...Ints> 
void foo(Ints...args) 
{ 
    constexpr size_t sz = sizeof...(args); 
    static_assert(sz <= 15, "foo(ints...) only support up to 15 arguments"); // This is the only limit on the number of args. 

    vector<int> v = {args...}; 

    vfoo(v); 
} 


int main() { 
    foo(1); 
    foo(1, 2, 99); 
    foo(1, 4, 99, 2, 5, -33, 0, 4, 23, 3, 44, 999, -43, 44, 3); 
    // foo(1, 4, 99, 2, 5, -33, 0, 4, 23, 3, 44, 999, -43, 44, 3, 0); // This will not compile 

    // You can also call the non-template version with a parameter pack directly: 

    vfoo({4, 3, 9}); 

// Downside is that errors will not be great; i.e. .this 
// foo(1.0, 3, 99); 
// /Users/jcrotinger/Work/CLionProjects/so_variadic_int_function/main.cpp:21:22: error: type 'double' cannot be narrowed to 'int' in initializer list [-Wc++11-narrowing] 
// vector<int> v = {args...}; 
// ^~~~ 
//   /Users/jcrotinger/Work/CLionProjects/so_variadic_int_function/main.cpp:38:5: note: in instantiation of function template specialization 'foo<double, int, int>' requested here 
// foo(1.0, 3, 99); 
// ^

    return 0; 
} 

静态断言是将其限制为15所争论的唯一的事情。如注释所示,类型检查很麻烦,因为错误消息不是来自函数调用,而是来自向量的初始化。

这确实需要支持C++ 11的可变参数模板。