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
所以問題是這樣的:你想要一個答案,顯示C++的方式做到這一點?你的嘗試太長,並且有錯誤(編譯器和邏輯錯誤)。 – PaulMcKenzie 2014-11-06 16:12:35
如果你能告訴我一些其他的做法,我會非常感謝。你也可以解釋我什麼是邏輯錯誤? – hallelujah 2014-11-06 16:15:16
我急於推薦使用'std :: string'而不是原始的'char *'指針。 – 2014-11-06 16:15:19