我想寫一個文本文件,並從文本文件中讀取來獲得項目的平均得分在數組中。這裏是我的代碼:讀取和寫入文件到陣列
#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++ << " " ;
}
但現在我有另一個問題,就是我無法讀取該文件,並計算平均水平。任何人都知道如何解決?
您所看到的文件中的一個指針的地址,因爲語句'out_file正在到來<<&A;'。 – Mahesh