向后打印列表

Printing list backwards

本文关键字:列表 打印      更新时间:2023-10-16

我有一个问题,这个程序是向前和向后打印出一个列表,但是当我向后打印出列表时,列表中的第一个数字是一个随机的大量数字,而不是正确的数字。例如

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] << " ";
}

这是罪魁祸首:

array1[x] = x;

如果你的数组输入值是0 1 2 3 4 5 6 7 8 0,那么在循环的最后一次迭代中,你正在做array1[0] = 0。重写数组中的第一项,同时增加计数器。然后,当你反转它array[9]包含垃圾值,因为你从来没有设置它。

您有一个问题,因为行array1[x]=x;。如果你的文件中的数字是0,你的代码实际上会工作。9,但最后的数字是另一个0,所以你不设置array1[9]为任何值

你应该有一些变量来索引数组,比如:

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

你在做什么

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

array1[9]未初始化

代码中有一些严重的问题:

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,因为最后一次读的是0,而array1[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;;

你向上计数错误,最终击中未初始化的内存后,你的数组。你应该把数组的长度作为参数传递给函数。
当数组衰减为指针时,您将无法恢复其长度。

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

那你就不用这么复杂地计算它的长度了