2015-04-02 116 views
1

我正在使用Visual Studio 2013,C++,控制檯應用程序。我現在一直在努力解決一個問題。我想知道是否有方法來初始化一個數組,例如用戶輸入,例如:用用戶輸入初始化一個數組

我有一個數組:int arr[] = { 3, 7, 5, 9, 1};。因此,我想要初始化的值是一個用戶輸入。

有沒有辦法做到這一點?所有的幫助和意見將不勝感激。

這是我的代碼: cout < <「輸入數組元素的數量:」; cin >>元素;

cout << "Enter the difference value: "; 
cin >> difference; 

cout << "Enter the sequence of elements: "; 

vector<int> arr(elements); 


for (int i = 0; i < elements; i++) 
{ 
    cin >> arr[i]; 

} 
//the following needs to have an array 
//in their respective functions. 
sorter(arr[], elements); 
elementsDifference(arr[], elements, difference); 

該程序必須遍歷一個數組,並找到具有給定差異的對。

回答

0

如何

int arr[10] , i; 
for (i = 0 ; i < 10 ; i++) 
    std::cin >> a[i]; 

這個簡單的代碼片段將採取來自用戶10級的輸入,並將它們存儲在數組中。

如果你想改變輸入的數量,你可以改變for循環的條件(同時確保你的數組有足夠的大小來存儲所有的值)。

UPDATE

,您可以嘗試這樣

int size; 
cin >> size; 
int a[size],i; 
for (i = 0 ; i < size ; i++) 
    cin >> a[i]; 
for (i = 0 ; i < size ; i++) 
    cout << a[i] << endl; 

通常情況下,人們只會使數組非常大(如a[100000]左右),然後接受尺寸的大小,並填寫該數組使用類似於上面給出的代碼。

但更好的方法是使用vector。你應該學會如何使用vector

+0

但是,在我的問題,數組的大小由用戶依賴於輸入例如,輸入元素的大小:然後用戶輸入元素的數量,那麼這將如何工作? @Arun A.S – 2015-04-03 08:12:50

+0

@PrathamPatel,爲此添加了代碼。 – 2015-04-03 08:18:38

0

如果您需要在C++中可變長度數組,你應該使用std::vector

std::cout << "Enter the number of elements: "; 
int n; 
std::cin >> n; 
std::vector<int> ints; 
ints.reserve(n); 

for (int i = 0; i < n; ++i) 
{ 
    std::cout << "Enter element #" << i + 1 << ": "; 
    int element; 
    std::cin >> element; 
    ints.push_back(element); 
} 
+0

我確實嘗試過,但沒有運氣,這裏是我的代碼,它可能有助於解釋我實際上在尋找什麼: – 2015-04-03 08:39:34

+0

cout <<「輸入數組元素的數量:」; \t cin >> elements; \t cout <<「輸入差值:」; \t cin >>區別; \t \t cout <<「輸入元素序列:」; \t vector arr(elements); \t \t對(INT I = 0; I <要素;我++) \t { \t \t CIN >>常用3 [I]; //這是在我要輸入數字 \t \t \t } \t //以下需要的序列以在它們各自的功能的陣列 \t //。 \t sorter(arr [],elements); \t elementsDifference(arr [],elements,difference); – 2015-04-03 08:40:50

+0

如果沒有C++ 11支持,您可以使用'arr.data()'或'&arr [0]'從vector獲取底層數組。例如。 'sorter(arr.data(),elements)'。 – emlai 2015-04-03 08:50:15