2015-04-02 29 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