[英]Zeros when printing out an array which is declared on the heap. C++
我想制作一個程序,讓用戶在數組中插入一些數字,然后將其打印出來。 問題是當我嘗試這樣做時(假設我的數組的大小是 100)然后:它應該做什么:Inserted- 1,2,3,4,5
-> 應該打印1,2,3,4,5
但是它打印 -> 1,2,3,4,5,0,0,0,0,0,0, ....
直到我的數組的大小。 有什么辦法可以擺脫這些零嗎? 代碼:
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;
}
事先獲取用戶輸入的numOfElements
。 例如
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;
}
輸入
4
10 20 30 40
輸出
10 20 30 40
無論用戶輸入什么,您都會增加numOfElements
。 只需這樣做:
if(isdigit(numbers[i]))
{
numOfElements++;
}
這將計算數字,而不是字符。 如果您希望用戶輸入多位數的數字,當然可能仍然太粗糙。
由於您聲明了數組大小,因此所有索引都將為零。 用戶輸入僅將前 x 個索引從零更改為輸入的值(從左到右)。 所有其他索引保持 0。如果您只想輸出不同於 0(用戶輸入)的整數,您可以執行以下操作:
for(auto x : numbers){
if(x!=0)cout<<x<<" ";
}
您可以使用 vector 和 push_back 用戶輸入中的值來精確獲得所需的大小而無需零,然后您可以使用以下簡單代碼:
for(auto x : vectorName)cout<<x<<" ";
以前使用計數器的解決方案很好。 否則你可以(在一段時間內......或類似的)
當您打印表單 0 到計數器時,您將只獲得非零值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.