C++ After I use getline to read from a file I can no longer write to the txt file

南楼画角 提交于 2019-12-11 15:04:23

问题


I am able to write to a text file then I use getline and I can no longer write to the file.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
 ifstream infile;
 fstream crypto;
 ofstream hacker;
 string tempString;
 string tempString2;
 string plaintext;
 string line;
 string dec;
.
.
.
crypto<<"hello";//write some stuff to file here
use getline(crypto, line, '\n')
crypto<<"hi";//Doesnt write to file anymore. 

回答1:


Files have a single error status and a shared file-position indicator, which is used for both read and write operations.

If the error status is set, then neither read nor write operations will succeed on the file. Reading past the end of the file is one trigger that will cause the error status to be set, in this case until the file-position indicator is repositioned within the bounds of the file.

As there is only a single position indicator for both reading and writing, you need to reposition that indicator each time you switch between reading and writing the same file to ensure that you are performing the next operation at the position where you intend it to occur.




回答2:


It's a bit hard to see from your code as is (try returns after each line) but I guess you've set the file access to read.




回答3:


The file has entered an error state.

Once the file is in an error state then all io operations will be ignored until you reset the error state. So basically the above suggests that the getline operation failed in some way.



来源:https://stackoverflow.com/questions/4074628/c-after-i-use-getline-to-read-from-a-file-i-can-no-longer-write-to-the-txt-fil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!