【发布时间】:2016-02-09 04:03:26
【问题描述】:
我应该写一些代码让用户输入一个数组(1.3 4 5.2 16.3 9.99 7.21 4.5 7.43 11.21 12.5)。
之后,我创建了一个更大的新数组(两倍大小),将旧数组中的所有元素复制到新数组中,然后要求用户继续向新数组中输入 5 个元素: 1.5 4.5 9.5 16.5 7.5 11.5,然后打印出最终的数组(15个元素)。
这是我的代码:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
double* read_data(int& size)
{
int max = 10;
double* a = new double[max]; // allocated on heap
size = 0;
cout << "Enter the array: " << endl;
while (cin >> a[size])
{
size++;
}
if (size >= max)
{
double* temp = new double[max * 2];
for (int i = 0; i < size; i++)
{
temp[i] = a[i];
}
delete[] a;
a = temp;
max = max * 2;
}
return a;
}
int main ()
{
int input1, input2, input3, input4, input5;
int size = 0;
double* arr = read_data(size);
cout << "Please enter 5 more elements: " << endl;
cin >> input1 >> input2 >> input3 >> input4 >> input5;
arr[10] = input1;
arr[11] = input2;
arr[12] = input3;
arr[13] = input4;
arr[14] = input5;
cout << "The final array is: " << endl;
for (int i = 0; i < 15; i++)
{
cout << arr[i];
}
system("pause");
return 0;
}
它不允许我再输入 5 个元素,我不知道为什么。 请帮忙。
【问题讨论】:
-
“它不允许我再输入 5 个元素”是什么意思?
-
我的意思是在 cout
-
它跳过下面的整个部分,输出只有10个元素
-
它如何知道在第一个循环中何时停止阅读元素?
while (cin >> a[size]) {size++;}会读取尽可能多的元素,而不关心数组大小。 -
嗯,我输入 q 退出; __ ;
标签: c++ arrays dynamic-memory-allocation