2013-04-23 98 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;;