gpt4 book ai didi

c++ - 读取文件时打印出正确的值,但在读取文件后打印出垃圾

转载 作者:行者123 更新时间:2023-11-28 00:25:56 27 4
gpt4 key购买 nike

问题:为什么它在 while 循环内(读取/输入文件时)打印出正确的值,而在 while 循环外却不打印?我不明白。非常感谢您的帮助。

输入文件:

1
2
3
4
5

#include <iostream>
#include <string>
#include <fstream>
#include <string>

using namespace std;

int sumNumbers(int sum, int* numbers, int numElements, int count)
{
if (count == numElements) return sum;

sumNumbers(sum + numbers[count], numbers, numElements, count + 1);

return 0;
}

int main(int argc, char* argv[])
{
int* numbers;
int numElements = 0;;
int sum = 0;

string fileName = argv[2];

ifstream ifile(fileName);

if( ifile.fail() ) {
cout << "The file could not be opened. The program is terminated." << endl;
return 0;
}

while ( !ifile.eof() ) {
numbers = new int[++numElements];
ifile >> numbers[numElements - 1];
cout << "Position " << numElements - 1 << ": " << numbers[numElements - 1] << endl;
}

cout << numbers[0] << endl;
cout << numbers[1] << endl;
cout << numbers[2] << endl;
cout << numbers[3] << endl;
cout << numbers[4] << endl;

cout << "--------------\n";

for(int i = 0; i < numElements; i++) {
cout << "Position " << i << ": " << numbers[i] << endl;
}

sumNumbers(sum, numbers, numElements, 0);

cout << "The sum of the numbers in the file is: " << sum << endl;

return 0;
}

输出:

Position 0: 1
Position 1: 2
Position 2: 3
Position 3: 4
Position 4: 5
0
-805306368
0
-805306368
5
--------------
Position 0: 0
Position 1: -805306368
Position 2: 0
Position 3: -805306368
Position 4: 5
The sum of the numbers in the file is: 0

最佳答案

您在每次循环迭代中实例化(并泄漏)了一个新数组。而且您只填充该数组的一个元素。循环结束后,您将得到最终数组,其中只有最后一个元素集。

SO 上有很多题都是处理从文件中读取数字到数组或容器中的问题。在这里,数字被读入 std::vector。 .

#include <fstream>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>

int main()
{
std::vector<int> numbers;
ifstream ifile(fileName);
std::istream_iterator<int> eof;
std::istream_iterator<int> it(ifile);
std::copy(it, eof, std::back_inserter(numbers));

for(int i = 0; i < numbers.size(); ++i)
{
cout << "Position " << i << ": " << numbers[i] << endl;
}

}

或者,您可以用 while 循环替换 istream_iterators 和对 std::copy 的调用:

int n=0;
while (ifile >> n) {
numbers.push_back(n);
}

关于c++ - 读取文件时打印出正确的值,但在读取文件后打印出垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25112751/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com