简体   繁体   English

打印出在堆上声明的数组时为零。 C++

[英]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.问题是当我尝试这样做时(假设我的数组的大小是 100)然后:它应该做什么:Inserted- 1,2,3,4,5 -> 应该打印1,2,3,4,5但是它打印 -> 1,2,3,4,5,0,0,0,0,0,0, ....直到我的数组的大小。 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.事先获取用户输入的numOfElements 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.无论用户输入什么,您都会增加numOfElements 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).用户输入仅将前 x 个索引从零更改为输入的值(从左到右)。 All other indices remains 0. If you want to output only integers different from 0 (user input) you can do something like that:所有其他索引保持 0。如果您只想输出不同于 0(用户输入)的整数,您可以执行以下操作:

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:您可以使用 vector 和 push_back 用户输入中的值来精确获得所需的大小而无需零,然后您可以使用以下简单代码:

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)如果计数器 >= SIZE-1 则退出循环(达到最大插槽)
  4. increment counter递增计数器

when You will print, form 0 to counter, you will get only non zero values.当您打印表单 0 到计数器时,您将只获得非零值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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