我的目标是让玩家为一个数组输入一组数字,然后将该数组写入一个文本文件。它的另一个部分是能够从文本文件中接收一组数字,并将它们放入从最高到最低的排序数组中,然后输出该数组。但由于某些原因,我收到了很多错误,我觉得通过一些研究我可以修复这些错误。不幸的是,有一种非常混乱的情况,我通过输出数组的每个元素来测试以确保未排序的数组是正确的。这不是最终程序的一部分,而是目前的测试。我有一个for循环可以做到这一点,它工作得很好,按照预期输出每个数字。然后在下一个for循环中,完全相同的事情应该会发生,但输出的数字都是乱七八糟的。我不明白是怎么回事。下面的代码
void readFile(string fName) {
string fileName = fName + ".txt";
ifstream myFile(fileName);
char c;
string num;
int count = 0;
// Bring the array from file to int array
while (!myFile.eof()) {
myFile.get(c);
if (isspace(c) && num != "") {
int n = stoi(num);
intArray[count] = n;
count++;
num = "";
continue;
}
if (!myFile.eof()) {
num += c;
}
}
for (int i = 0; i < 10; i++) {
cout << intArray[i] << endl;
}
// Sort the array higest to lowest
for (int i = 0; i < 10; i++) {
cout << intArray[i] << " ";
for (int j = 9; j >= i; j--) {
if (j == 0) {
continue;
}
if (intArray[j] > intArray[j - 1]) {
int temp = arr[j];
intArray[j] = intArray[j - 1];
intArray[j - 1] = temp;
}
}
cout << endl;
}
}很抱歉上面的格式,它很奇怪,所以想象一下代码在函数中。
这是输出的结果:
1
2
3
4
5
6
7
8
99
234
1
1
1
1
1
1
1
1
1
11系列前面的数字是实际的数组,1显然是根据最后一段代码中的cout的数组,其中cout << intArrayi
发布于 2019-11-21 08:29:48
您的数组似乎已排序。打印所有文件的原因是由于cout <<在外部循环中的位置。
考虑一下您的数组在通过内部循环进行第一次迭代后的样子:
234,1,2,3,4,5,6,7,8,99
现在考虑一下,您在外部循环中将i递增为1。当您为数组intArray[i]编制索引时,i的th元素现在是1,因为您正确地将它移到了那里。每次,您都将较小的元素在数组中向上移动一个位置,然后索引到1所在的位置。
在排序时,不要尝试打印已排序的数组。相反,循环遍历它并在排序后打印它。
https://stackoverflow.com/questions/58965193
复制相似问题