我已经创建了一个函数来在文本文件上写入一些数据,并且它工作正常。我创建了另一个函数来读取文件的所有内容,并为我打印出来!但是,由于某种原因它不起作用。任何人都可以帮忙吗?我无法打印出我在
这是我的函数:
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())'。 –