读取&将文件写入数组 [英] Read & Write file into array

查看:88
本文介绍了读取&将文件写入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write to a text file and read from text file to get the average score of items in an array. Here is my code:

#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;
}

但是,这个程序只是简单地执行而不从文件中读取,平均分。这是我在我的文本文件中获取的:

However, this program just simply execute without reading from a file and return the correct average score. And this is what I get in my text file :


0035FDE8

0035FDE8

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

I thought it supposed to write the entire array into text file, and from there I retrieve the elements and calculate for the average?

已编辑部分

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

I have fixed the writing to text file part using a for loop on pointer :

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

但现在我有另一个问题,我无法读取文件和计算平均值。

But now I having another problem which is I cannot read the file and compute for the average. Anybody know how to fix?

推荐答案

您可以尝试这样

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;

这篇关于读取&amp;将文件写入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆