2013-12-17 67 views
0

我在嘗試讀取外部文本文件時遇到問題。 顯示的文本是正確的,但是當涉及到將數據保存到數組中時,它似乎是錯誤的。ifstream嘗試將數據保存到數組時遇到錯誤

我的輸入數字是4 2 8 0 2 3 0 4 0 5,但是在遍歷數組後,a [i]只出現'48'。

#include <iostream> 
#include <windows.h> 
#include <fstream> 
#include <string> 

void begin(); 
void Process (string); 

using namespace std; 

int main() 
{ 

     begin(); 

     system("pause"); 
     return 0; 
} 

void begin (void){ 

string file = "data.txt"; 
Process(file);  
} 

void Process (string file) 
{ 

     int i=0,ch, n = 0, temp, a[50]; 


     ifstream infile; 
     infile.open(file.c_str()); 

該錯誤似乎是由此引起的。

 if(infile.is_open()) 
     { 

      cout << "File to be read: " << file << endl; 
      cout << "\n\n"; 
      infile >> temp; 
      while(!infile.fail()) 
      { 
       cout << temp << " "; 
       infile >> temp; 
       a[i] = temp; 
       i++; 
       n++; 
      } 

     cout << "\n\n"; 
     cout << "This file has " << n << " numbers. \n\n"; 

     } 

     else 
      cout << "The file isn't available! \n\n"; 

     infile.close(); 

當我嘗試輸出結果時,只出現了48。

 for (int z = 0; z < i; z++) 
     { 
      cout << a[i] << endl; 

     } 
} 

我是新來的。請幫忙。提前致謝。

回答

1

您的顯示迴路使用i代替z索引到a(這應該是爲什麼變量命名是很重要的一個很好的教訓!)你的顯示器循環改成這樣:

for (int z = 0; z < i; z++) 
    { 
     cout << a[z] << endl; 
    } 

有可能更問題與您的代碼,但這似乎是什麼阻止你。考慮將ia重命名爲更有意義的事情。花費在打字上的時間總是會讓你花費時間去理解你的意思。

0

考慮這個循環

for (int z = 0; z < i; z++) 
    { 
     cout << a[i] << endl; 

    } 

你總是輸出一個元素的[I]而不是[Z]。此外,索引爲i的元素未分配。最後指定的元素是[i-1]。

除此之外,您不會將第一個輸入的數字保存在數組中。您開始保存來自第二個號碼的輸入數據。

 infile >> temp; // <== this value was not assigned to an element of the array 
     while(!infile.fail()) 
     { 
      cout << temp << " "; 
      infile >> temp; 
      a[i] = temp; 

而且循環

  infile >> temp; 

這裏面的語句可能會導致錯誤。所以之後沒有意義寫

  a[i] = temp; 

因爲沒有輸入任何內容,事實上你會將前一個數字存儲在下一個元素中。

相關問題