2017-08-20 34 views
-1

這些值正確地存儲在「arr」中,但垃圾值被存儲在「str」中。我不懂爲什麼。我檢查過很多次,這對我來說似乎是正確的。這些值正確存儲在「arr」中,但垃圾值正在存儲在「str」中。我不明白爲什麼

#include <iostream> 
using namespace std; 

int main() { 
    int test,n,arr[50],str[20][20],i,j,k; 
    t = 0; 
    j = 0; 
    cin>>test; //test cases 
    while(test>0){ 
     cin>>n; //number of elements in a test case 
     for(i=0;i<n;i++) 
      cin>>arr[i]; //array of elements 
     for(i=0;i<n;i++){ 
      cout<<"arr = "<<arr[i]<<"\n"; 
      str[i][j] = arr[i]; // storing arr in str 
     } 
     cout<<"\n"; 
     str[i+1][j] = 0; 
     j++; 
     test--; 
    } 
    for(i=0;i<j;i++){ 
     for(k=0;str[i][k]!=0;k++) 
      cout<<<<str[i][k]; // printing str 
     cout<<"\n"; 
    } 
    return 0; 
} 
+1

你應該用你的調試器,並期待在值。 –

+0

我正在查看所有值,值正確存儲在「arr」中,但是當我打印「str」時,正在顯示垃圾值。我認爲在爲str分配值時我犯了一些錯誤。 –

+0

您不應在其他'char'數組中使用'0'作爲空終止符。 –

回答

1

有很多失誤,但最主要的是一個二維數組的索引

的二維數組是這樣ARR [行] [列],你一直在使用它像ARR [專欄] [行]

str[i][j] = arr[i]; 

看到什麼ü在​​做每行存儲號碼

也許這個形象將清除的東西出來

enter image description here

#include <iostream> 
using std :: cin ; 
using std :: cout ; 
using std :: endl ; 

int main() { 
    int test,n,arr[50],str[20][20],i,j,k; 
    j = 0; 
    cin>>test; //test cases 
    int temp = test ; 
    while(test>0) 
    { 
     cin>>n; //number of elements in a test case 

     for(i=0;i<n;i++) 
      cin>>arr[i]; //array of elements 

     for(i=0;i<n;i++) 
     { 
      cout<<"arr = "<<arr[i]<<"\n"; 
      str[j][i] = arr[i]; // storing arr in str 
     } 

     str[j][i] = '\0'; 
     cout<<"\n"; 

     j++; 
     test--; 
    } 

    for (int i = 0 ; i < temp ; i++) 
    { 
     j=0 ; 
    while (str[i][j] != '\0') 
     { 
      cout<<str[i][j]; // printing str 
      j++ ; 
     } 
     cout<<"\n"; 
    } 
    cin.ignore(5) ; 
    return 0; 
} 
+0

謝謝,它工作。 –

0

首先,你從不使用't',所以我刪除了它。 我發現它實際上並不是真的輸出垃圾值,它只是以錯誤的順序輸出值。如果你在最後交換k和我,它應該工作:

#include <iostream> 
using namespace std; 

int main() { 
    int test,n,arr[50],str[20][20],j,i,k; 
    j = 0; 
    cin>>test; //test cases 
    while(test>0){ 
     cin>>n; //number of elements in a test case 
     for(i=0;i<n;i++){ 
      cin>>arr[i]; //array of elements 
     } 
     for(i=0;i<n;i++){ 
      cout<<"arr = "<<arr[i]<<"\n"; 
      str[j][i] = arr[i]; // storing arr in str 
     } 
     cout<<"\n"; 
     str[j+1][i] = 0; 
     j++; 
     test--; 
    } 
    for(i=0;i<j;i++){ 
     for(k=0;str[k][i]!=0;k++){ 
      cout<<str[k][i]<< ' '; // printing str 
     } 
     cout<<"\n"; 
    } 
    return 0; 
} 
+0

輸入也是錯誤的,因爲他在每一行都加了一個數字 –

+1

我已經意識到,我一定忘了在代碼中改變它,現在我只是改變了它。 – EmberWolf77

相關問題