#include <iostream>
#include <cctype> // for isdigit function
int main()
{
int initial_size = 10;
int* temp = new int[initial_size];
int actual_size = 0;
while ( 1 )
{
char ch;
cin >> ch;
if ( ch == 'E' )
break;
if ( isdigit(ch) ){
cin.unget();
int n;
cin >> n; //If it's an integer, store it.
actual_size++; // Keep tracks of actual size.
if ( actual_size <= initial_size )
*temp++ = n; //Storing in temp array...
else if ( actual_size > initial_size ){ //When there's not enough space in array..
int old_initial_size = initial_size;
initial_size *= 2; //Doubling the size of initial_size after storing it in old_initial_size.
int* hold = new int[old_initial_size];
for ( int i = 0; i < old_initial_size; i++)
hold[i] = temp[i]; // From temp to hold.This is my attempt at keeping the values of temp array.
temp = new int[initial_size]; // After passing every value in temp i resize it.
for ( int i = 0; i < old_initial_size; i++)
temp[i] = hold[i]; //From hold to newly created temp.
delete[] hold;
}
}
}
int* actualArray = new int[actual_size];
for ( int i = 0; i < actual_size; i++)
actualArray[i] = temp[i];
delete[] temp;
for ( int i = 0; i < actual_size; i++)
cout << actualArray[i] << " ";
}
这就是我想要做的:
我想从用户那里获取输入,直到输入 E。如果输入是一个整数,我想将它存储在一个大小为 10 的预定义临时动态数组中。
在这样做的同时,我想计算数字输入的实际数量。如果超过临时数组的初始大小,我想将临时数组的大小加倍,同时将旧输入保留在其中。
当循环终止时,我想将临时数组中的输入传递给我的实际数组,其大小与数字输入完全相同。(实际大小)
您可以在上面看到我的尝试。作为输出,我得到的只是随机数,但至少我得到了正确数量的随机数。
例如,如果我输入3 4 E
,我会得到类似13123213 1541321231