我正在构建一个大型文件 I/O 库,目前正在努力解决 getline() 的互操作性和写入文件。我下面的问题很像这个问题,不幸的是仍然没有答案:C++ After I use getline to read from a file I can no longer write to the txt file
一旦我使用了 getline(),我就不能再写入文件了。使用 getline() 的读取请求将继续运行,但写入请求将失败。但是,如果我注释掉 getline() 的用法,写操作就会成功。
我的代码发布在下面。我注意到在第一次写入尝试后故障位被激活。但是,我不知道发生这种情况的原因,因为如果我删除 getline() 操作,它就不会激活。
我应该清楚——我可以完美地从现有文件(包含两行)中读取。但是,我无法写入该文件,除非我删除 getline() 语句。
任何帮助,一如既往地受到赞赏。
// Includes
#include <fstream>
#include <iostream>
#include <string>
// Namespace
using namespace std;
int main(){
// filestream object
fstream workFile("testdoc.txt"); //fstream uses ios::in | ios::out by default
// note that I have tried including ios::in | ios::out to no avail
// read from file
string grabbedLine;
getline(workFile, grabbedLine);
cout << "Line #1: " << grabbedLine << endl;
// write to file
workFile<< "Here is some output (#1)" << endl;
// read from file
getline(workFile, grabbedLine);
cout << "Line #2: " << grabbedLine << endl;
// write to file
workFile<< "Here is some output (#2)" << endl;
// wait for some input...
getchar();
}
Current console output (as expected from text file):
Line #1: This is line#1
Line #2: This is line#2