[英]I Can't print out a file that I wrote on
我创建了一个在文本文件上写入一些数据的功能,并且工作正常。 我创建了另一个函数来读取文件的所有内容,并为我打印出来! 但是,由于某种原因,它不起作用。 有人可以帮忙吗?
这是我的功能:
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();
}
愚蠢的我,造成问题的原因从一开始就直面我,而问题在于app
开放模式。 它将以写模式打开文件,这意味着您无法从中读取文件。
即使您可以从文件中读取内容,也可以将光标放置在文件的末尾,无论如何, eofbit
标志还是会在第一次迭代中设置的。
如果要读取文件,请使用std::ifstream
,如果您未指定模式,它会自动设置in
模式,或者在打开时必须显式设置in
模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.