简体   繁体   中英

Zeros when printing out an array which is declared on the heap. C++

I want to make a program that lets the user insert some numbers to the array and the print it out afterwards. Problem is when I try to do that (lets say the size of my array is 100) then: What it should do: Inserted- 1,2,3,4,5 -> should print 1,2,3,4,5 But instead it prints -> 1,2,3,4,5,0,0,0,0,0,0, .... up to the size of my array. Is there any way I can get rid of those zeros? Code:

int SIZE = 100;
int main()
{
int *numbers;
numbers = new int[SIZE];
int numOfElements = 0;
int i = 0;
cout << "Insert some numbers (! to end): ";
while((numbers[i] != '!') && (i < SIZE)){
    cin >> numbers[i];
    numOfElements++;
    i++;
}
for(int i = 0; i < numOfElements; i++){
    cout << numbers[i] << " ";
}
delete [] numbers;
return 0;
}

Get numOfElements entered from user beforehand. For example

int main() {
    int n;
    cin >> n;
    int * a = new int[n];
    for (int i = 0; i < n; ++i)
        cin >> a[i];
    for (int i = 0; i < n; ++i)
        cout << a[i] << endl;
    delete[] a;
}

Input

4
10 20 30 40

Output

10 20 30 40

You increase numOfElements no matter what the user types. Simply do this instead:

if(isdigit(numbers[i]))
{
  numOfElements++;
}

This will count digits, not characters. It may of course still be too crude if you want the user to input numbers with multiple digits.

Since you declared array size, all indices will be zeros. User input changes only the first x indices from zero to the value entered (left to right). All other indices remains 0. If you want to output only integers different from 0 (user input) you can do something like that:

for(auto x : numbers){
if(x!=0)cout<<x<<" ";
}

You can use vector and push_back the values from user input to get exactly the size you need without zeros, then you can use this simple code:

for(auto x : vectorName)cout<<x<<" ";

Previous solutions using a counter is fine. otherwise you can (in a while... or similar)

  1. read values in a "temp" var
  2. add if temp non zero
  3. exit loop if counter >= SIZE-1 (you reach max slots)
  4. increment counter

when You will print, form 0 to counter, you will get only non zero values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM