阅读&将文件写入数组

时间:2013-05-15 13:40:53

标签: c++ arrays pointers file-io

我正在尝试写入文本文件并从文本文件中读取以获取数组中项目的平均分数。这是我的代码:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
float total =0;;

ofstream out_file;
out_file.open("number.txt");

const int size = 5;
double num_array[] = {1,2,3,4,5}; 

for (int count = 0; count < size; count++)
{
    if (num_array[count] == 0)
    {
        cout << "0 digit detected. " << endl;
        system("PAUSE");
    }
}
double* a = num_array;
out_file << &a;

out_file.close();

ifstream in_file;
in_file.open("number.txt");
if(in_file.fail())
{
    cout << "File opening error" << endl;
}else{
    for (int count =0; count< size; count++){
        total += *a;  // Access the element a currently points to
        *a++;  // Move the pointer by one position forward
    }
}

cout << total/size << endl;

system("PAUSE");
return 0;
}

然而,这个程序只是简单地执行而不从文件中读取并返回正确的平均分数。这就是我在文本文件中得到的内容:

  

0035FDE8

我认为它应该将整个数组写入文本文件,并从那里检索元素并计算平均值?

已编辑的部分

我已经使用指针上的for循环修复了对文本文件部分的写入:

for(int count = 0; count < size; count ++){
    out_file << *a++ << " " ;
}

但现在我有另一个问题,即我无法读取文件并计算平均值。有人知道怎么修理吗?

2 个答案:

答案 0 :(得分:2)

您正在将指向数组的指针的地址写入文件,而不是数组本身。

out_file << &a;

因此,您在文件中获得0035FDE8,这是一个地址。

您可以在out_file<<num_array[count]循环中使用for将每个值写入文件。 您还将使用类似的for循环阅读。

答案 1 :(得分:1)

您可以尝试这样的事情

double total =0;

    std::ofstream out_file;
    out_file.open("number.txt");

    const int size = 5;
    double num_array[] = {1,2,3,4,5}; 

    for (int count = 0; count < size; count++)
    {
        if (num_array[count] == 0)
        {
            std::cout << "0 digit detected. " << std::endl;
            system("PAUSE");
        }
        else
        {
            out_file<< num_array[count]<<" ";    
        }
    }
    out_file<<std::endl;
    out_file.close();
    std::ifstream in_file;
    in_file.open("number.txt");
    double a;
    if(in_file.fail())
    {
        std::cout << "File opening error" << std::endl;
    }
    else
    {
        for (int count =0; count< size; count++)
        {
            in_file >> a;
            total += a;  // Access the element a currently points to
        }
    }

        std::cout << total/size << std::endl;