从dat文件读入数组

时间:2015-02-10 20:17:24

标签: c++

我是一名一年级学生,我正忙于编码练习,但似乎无法解决这个问题。

当从number.dat读取20个随机数时,我将它们读入数组并在此阶段打印它们仅用于诊断但是我在数组中的数据打印完全搞砸了。

非常感谢任何帮助。

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
    ifstream in_stream;
    ofstream out_stream;

    int array_size = 20;
    int position = 0;
    double numbers[array_size];

    //Check input and output file.
    in_stream.open("Number.dat");
    if (in_stream.fail())
    {
        cout << "Input file opening failed";
        exit(1);
    }

    //array to read data from array as long as we dont reach the end of file marker
    while(! in_stream.eof() && position < array_size)
    {
        in_stream >> numbers[position];
        position++;
        cout << position << " = "
             << numbers[position] << endl;
    }

}

3 个答案:

答案 0 :(得分:4)

有两个问题,一个问题不是这个特定问题的原因。

首先,使用while (!instream.eof()会导致您读取的次数太多,因为eof()在之后的第一次尝试读取之后才会变为真成功的。

但直接原因是您在阅读和打印之间递增了position,因此您还要打印尚未设置的值。

试试这个:

while (position < array_size && in_stream >> numbers[position])
{
    cout << position << " = "
         << numbers[position] << endl;
    position++;
}

答案 1 :(得分:0)

你正在阅读尚未被填充的阵列部分,所以你应该得到垃圾,试试这个:

    while(! in_stream.eof() && position < array_size)
    {
        in_stream >> numbers[position];
        cout << position << " = "
             << numbers[position] << endl;
        position++;
    }

答案 2 :(得分:0)

根据上面的答案,我的问题是我在打印之前增加了我的循环变量,所以它试图打印数组中的下一个值。

谢谢大家的帮助

while(! in_stream.eof() && position < array_size)
{
    in_stream >> numbers[position];
    cout << position << " = "
         << numbers[position] << endl;
    position++;
}