2013-05-15 134 views
0

我想寫一個文本文件,並從文本文件中讀取來獲得項目的平均得分在數組中。這裏是我的代碼:讀取和寫入文件到陣列

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

但現在我有另一個問題,就是我無法讀取該文件,並計算平均水平。任何人都知道如何解決?

+0

您所看到的文件中的一個指針的地址,因爲語句'out_file正在到來<<&A;'。 – Mahesh

回答

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; 
+0

它的工作原理。非常感謝。所以基本上我可以不用指針就可以做到 – Yvonne

+0

是的,它可以不使用指針。所以一次只能讀一個數字。 – praks411

+0

很酷,非常感謝 – Yvonne

2

你正在寫的指針的地址到陣列到文件,而不是數組本身。

out_file << &a; 

因此,你這是一個地址在文件中得到0035FDE8

您可以通過在for循環使用out_file<<num_array[count]寫每個值到文件中。 你也可以選擇使用類似for循環讀取。

+0

@Yvonne你必須通過索引操作符訪問它的實際值來將每個元素寫入文件。 'out_file <<一個[0] << 「」 <<一個[1];' – Mahesh

+0

我使用的for循環,例如:用於(詮釋計數= 0;計數<大小;計數++){ \t out_file < <* a ++ <<「」; \t}它是固定的。但是還有另外一個問題,程序沒有從文件 – Yvonne

+0

@Yvonne讀 - 如果你是在一個循環寫,你也有一個循環讀取。 – user93353