2014-11-21 24 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的可變參數模板。