简体   繁体   中英

Read & Write file into array

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

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

Edited Portion

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?

You are writing the address of the pointer to the array into the file, not the array itself.

out_file << &a;

Hence you get 0035FDE8 in the file which is an address.

You can write each value into the file by using out_file<<num_array[count] in a for loop. You will also have read using a similar for loop.

You can try something like this

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM