我已經創建了一個函數來在文本文件上寫入一些數據,並且它工作正常。我創建了另一個函數來讀取文件的所有內容,併爲我打印出來!但是,由於某種原因它不起作用。任何人都可以幫忙嗎?我無法打印出我在
這是我的函數:
void myClass::displayFile() {
char line[LINE]; //to hold the current line
file.open("data.txt", ios::app);
//keep reading information from the file while the file is open and has data
while (!file.fail() && !file.eof()) {
int lineSize; //to loope through each line
file.getline(line, LINE);
lineSize = strlen(line);
//loop through the line to print it without delimiters
for (int i = 0; i < lineSize; ++i) {
if (line[i] == ';') {
cout << " || ";
} else {
cout << line[i];
}
}
}
file.close();
file.clear();
if (file.fail()) {
cerr << "Something went wrong with the file!";
}
}
注:該函數編譯和循環是可訪問的,但行字符串爲空。
這是寫入功能:
void myClass::fileWriter() {
file.open("data.txt", ios::app);
file << name << ";" << age << ";" << "\n";
file.close();
file.clear();
}
我試過你的代碼在我的一個文件上,我可以看到它打印的內容..你可以檢查你的文件是否實際寫入正確 – Megha
爲什麼你打開追加模式,你沒有寫入文件?爲什麼你使用不同的尺寸來聲明'line'和'getline'調用? ['std :: string'](http://en.cppreference.com/w/cpp/string/basic_string)和['std :: getline']有什麼問題(http://en.cppreference.com/ w/cpp/string/basic_string/getline)(它們更安全並且不容易出現緩衝區溢出)?在循環之後檢查'file.fail()',在檢查之前你明確地清除標誌是行不通的。 –
哦,雖然[「爲什麼是」while(!feof(file))「總是錯誤的?」](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong )被標記爲C編程語言,但C++和相同的問題存在'while(!file.eof())'。 –