2013-04-23 97 views
0

我遇到了一個打印出列表向前和向後列表的問題,但是,當我向後打印列表時,列表中的第一個數字是一個隨機的數字而不是正確的數字。例如打印列表向後

0 1 2 3 4 5 6 7 8 0 
4286398 8 7 6 5 4 3 2 1 0 

任何人都可以解釋我的代碼有什麼問題請。

也有人可以告訴我如何將計數器從printList函數傳遞給名爲checkList()的新函數,以便計數器在checkList()中具有與printList()的末尾相同的值。 。

代碼:

void printList(int array1[]){ 
int counter = 0; 
int x; 
ifstream theFile("list.txt"); 

while(theFile >> x){ 
    array1[x] = x; 
    cout << array1[x] << " "; 
    counter = counter + 1; 
} 
cout << endl << counter << endl;; 

int n = counter; 

for(int i = n -1; i >= 0; i--){ 
    cout << array1[i] << " "; 
} 
+3

它看起來像一個垃圾數量 – 2013-04-23 17:47:52

+0

什麼LIST.TXT的內容是什麼? – 2013-04-23 17:48:41

+0

它也看起來像你打印你的櫃檯。爲什麼不是你已經發布的輸出的一部分 – 2013-04-23 17:50:04

回答

4

你有因爲該行array1[x]=x;的問題。如果文件中的數字是0..9,那麼你的代碼實際上可以工作,但最終的數字是0,所以你不要將array1 [9]設置爲任何東西。

你應該有一些變量索引數組,是這樣的:

int counter = 0; 
while(theFile >> x){ 
    array1[counter] = x; 
    cout << array1[counter] << " "; 
    counter = counter + 1; 
} 
+2

如果他正在輸出他剛纔閱讀的內容,他還應該有'cout << array1 [counter]'。 – 2013-04-23 17:53:45

+0

是啊,對不起,錯過了那一行:) – James 2013-04-23 17:54:25

6

這裏的罪魁禍首:

array1[x] = x; 

如果陣列輸入值是0 1 2 3 4 5 6 7 8 0,然後在你的循環的最後一次迭代你正在做array1[0] = 0。這會覆蓋數組中的第一個項目,同時增加計數器。然後,當您將其倒轉時,array[9]包含垃圾值,因爲您從未設置它。

0

你正在向上計數錯誤,最終在你的數組後面打到未初始化的內存。您應該將數組的長度作爲參數傳遞給函數。
當數組衰減到指針時,您將無法恢復其長度。

void printList(int array1[], into size){ } 

那麼你並不需要弄清楚它的長度那麼複雜。

+2

實際上,他應該採用'std :: vector &',並使用'push_back'。然後他可以使用'rbegin()'和'rend()'輸出反向數組。 – 2013-04-23 17:52:40

+0

沒錯,但是如果OP想要使用數組,對我來說很好:-P – 2013-04-23 17:54:12

+0

考慮到問題的陳述方式,我懷疑它是作業,他必須使用C風格的數組,即使它是「錯誤的」這個背景。我有這樣的印象,那裏有很多壞教師。 – 2013-04-24 08:04:56

4

你正在做

array1[0] = 0; 
array1[1] = 1; 
array1[2] = 2; 
array1[3] = 3; 
array1[4] = 4; 
array1[5] = 5; 
array1[6] = 6; 
array1[7] = 7; 
array1[8] = 8; 
array1[0] = 0; // here 

數組1 [9]未初始化

1

你在代碼中有一些嚴重的問題:在

ifstream theFile("list.txt"); 
while(theFile >> x){ 
    array1[x] = x;//^^this is evil 
    cout << array1[x] << " "; 
    counter = counter + 1; 
} 
cout << endl << counter << endl;; 
          //^^extra colon, though not wrong here but not good practice 

您可以從文件中讀取並填充數組,你的特例,你有:

0 1 2 3 4 5 6 7 8 0 

你有10個元素,但你的array1將自9以來最後一次讀取的結果爲0array1[0]再次被寫爲0。所以當你輸出你的array1時,你永遠不會得到10數字,因爲你的數組實際存儲9個數字。這就是爲什麼當你嘗試訪問array1[9]時,你看到了垃圾值,這個值還沒有被填充,有些垃圾原始內存值。

相反,你可以嘗試做如下:

int counter = 0; 
int x; 
ifstream theFile("list.txt"); 

while(theFile >> x){ 
    array1[counter] = x; 
    cout << array1[counter] << " "; 
    counter = counter + 1; 
} 
cout << endl << counter << endl;;