2016-09-22 78 views
-5

我一直在試圖閱讀下面的文字.txt文件:.txt文件爲char數組?

調試是加倍努力在第一就是寫代碼。因此,如果您儘可能巧妙地編寫代碼,那麼根據定義,您的智能不足以進行調試。 - Brian W. Kernighan *

但是,當我嘗試將.txt文件發送到我的char數組時,整個消息除了單詞「Debugging」打印出來,我不知道爲什麼。這是我的代碼。它一定是簡單的,我看不到,任何幫助將不勝感激。

#include <iostream> 
#include <fstream> 

using namespace std; 

int main(){ 

char quote[300]; 

ifstream File; 

File.open("lab4data.txt"); 

File >> quote; 


File.get(quote, 300, '*'); 


cout << quote << endl; 
} 
+0

此代碼沒有意義,即使故意讀爲僞代碼。你能否請你嘗試改進你的問題來解釋你實際想要達到的目標。 –

+0

刪除'File >>引用;'這是當第一個單詞被寫入數組,然後被'File.get'的調用覆蓋時。 –

+0

謝謝,修正了 – Joe

回答

0

File >> quote; 

讀取第一個字到你的陣列。然後,下一個致電File.get的電話將複製您已閱讀的單詞。所以第一個詞就失去了。

您應該從您的代碼中刪除上述行,它將正常工作。

我通常會建議使用std::string而不是char數組讀取,但我可以看到ifstream::get不支持它,最接近的是streambuf

要注意的另一件事是檢查您的文件是否正確打開。

以下代碼可以做到這一點。

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 

int main(){ 

    char quote[300]; 
    ifstream file("kernighan.txt"); 

    if(file) 
    { 
     file.get(quote, 300, '*'); 
     cout << quote << '\n'; 
    } else 
    { 
     cout << "file could not be opened\n"; 
    }  
} 

ifstream目的是(在C++ 03世界或void*)轉換爲bool,因此可以防止對感實性進行測試。

0

一個簡單的字符由字符讀取方法(未測試)

包括
#include <fstream> 

using namespace std; 

int main() 
{ 
    char quote[300]; 
    ifstream File; 
    File.open("lab4data.txt"); 
    if(File) 
    { 
     int i = 0; 
     char c; 
     while(!File.eof()) 
     { 
      File.read(&c,sizeof(char)); 
      quote[i++] =c; 
     } 
     quote[i]='\0';   
     cout << quote << endl; 
     File.close(); 
    } 

}