2014-11-06 41 views
-2
class FilesHandling{ 
private: fstream f; 
     char *filename; 
public: char *dir; 
     int dir_no; 
     void readFile(char *c){ 
      ifstream f(c); 
      if (f.is_open()){ 
       int n; f >> n; 
       dir_no = n; 
       for (int i = 0; i < n; i++) 
       { 
       dir = new char[]; 
       f >> dir[i];}   
      f.close(); 
     } 
     else cout << "Can't open file" << endl; 
    } 

喜試。我希望你現在可以更容易理解代碼。我是新來的C++,我需要使用classes將數據從文件複製到數組中。這是我必須做的一個項目的一小部分。問題是,當我從main()調用方法時,它不會執行任何操作;我沒有收到任何錯誤,但是我看不到任何數據;從文件將文本複製到陣列中的類C++

FilesHandling f("dir_mon.txt"); 
cout << f.getFN() << endl; 
f.readFile("dir_mon.txt"); 
for (int i = 0; i < f.dir_no; i++) 
    cout << f.dir[i]; 

該班有其他成員,但我沒有在這裏複製他們;有什麼建議嗎? getFN()方法正在工作。我看不到

我搜索的讀取文件的另一種方法和使用的std :: string從txt文件複製的數據如你所說,但還是沒有結果。 這是新方法的樣子:

void getData(char *c){ 
    ifstream f(c); 
    if (f.is_open()){while(!f.eof()) 

     std::getline(f, line); 
     for (int i = 0; i <= line.size(); i++) 
      dir[i] = line; 
    }} 
    f.close(); 
} 
enter code here 
+0

所以問題是這樣的:你想要一個答案,顯示C++的方式做到這一點?你的嘗試太長,並且有錯誤(編譯器和邏輯錯誤)。 – PaulMcKenzie 2014-11-06 16:12:35

+0

如果你能告訴我一些其他的做法,我會非常感謝。你也可以解釋我什麼是邏輯錯誤? – hallelujah 2014-11-06 16:15:16

+0

我急於推薦使用'std :: string'而不是原始的'char *'指針。 – 2014-11-06 16:15:19

回答

0

有你的代碼的幾個問題。

1)錯誤使用new[]

2)不檢查以查看是否在該文件中的線實際上匹配(或超過)在dir_no值指定的行。

3)不必要的成員變量,如fstream f


這是一個工作示例。該示例使用以下內容:

1)代替std::vector<std::string> dirchar* dir,並std::string代替char*

2)的getline用法從文件中檢索的文本行。 3)請注意,當循環遇到dir_no項目時,或者文件用盡行時,無論哪個先發生,循環都將退出。

4)請看我們如何使用std::vector來擴展行數組。請注意,沒有使用new[]來執行此操作,而是調用成員函數std::vector

5)輸出的結果,所使用的算法功能std::copy的使用。你不需要現在就知道它做了什麼,只是讓你知道它做了什麼。

#include <string> 
#include <fstream> 
#include <vector> 
#include <iostream> 
#include <iterator> 
#include <algorithm> 

class FilesHandling 
{ 
    int dir_no; 
    std::vector<std::string> dir; 

    public: 
     void readFile(const std::string& fName) 
     { 
      std::ifstream f(fName.c_str()); 
      if (f) 
      { 
       f >> dir_no; 
       f.ignore(); 
       std::string line; 
       for (int i = 0; i < dir_no && getline(f, line); ++i) 
        dir.push_back(line); 

       // output the results for testing 
       std::copy(dir.begin(), dir.end(), std::ostream_iterator<std::string>(std::cout, "\n")); 
      } 
      else 
       std::cout << "Can't open file" << std::endl; 
     } 
    }; 

    int main() 
    { 
     FilesHandling fh; 
     fh.readFile("abc123.txt"); 
    } 

當你運行這個,你應該看到輸出到控制檯的文本行。

+0

非常感謝你!現在它工作。我會盡力從犯這些愚蠢的錯誤中學習 – hallelujah 2014-11-06 17:07:22

相關問題