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

时间:2014-08-04 06:17:37

标签: c++

问题:为什么它会在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

2 个答案:

答案 0 :(得分:2)

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

在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_iteratorsstd::copy的调用:

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

答案 1 :(得分:1)

这部分:

while ( !ifile.eof() ) {
        numbers = new int[++numElements];
        // ...

重复为numbers分配内存。在每个新的,先前的值丢失,并且先前分配的内存泄漏。您可以在下次调用new之前正确打印该值,以便它似乎在循环内工作。

最好使用vector

int new_number;
while ( ifile >> new_number) {
        numbers.push_back(new_number);
        // ...

并且不要使用file.eof() in the while condition