Why I can't read from file using “file_ptr>>variable” in my program?

柔情痞子 提交于 2019-12-31 07:07:19

问题


In the following program I am trying to understand how to read and write files.

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    fstream myfile;
    string str1;
    myfile.open("H:/input_file.txt");
    if(myfile.is_open())
    {   
    myfile<<"test1 writing files"<<" ";
    myfile>>str1;
    cout<<str1<<endl;
    }
    return 0;
}

Why I don't get any output on the console even though "test1 writing files" is written into a file?


回答1:


The file will need to be opened for both read and write (I'm sorry, ignore that; fstream is opened for both read & write by default). After writing (and flushing the output), you will need to seekg() back to the beginning of the file, or you will just be trying to read what comes after the last thing you wrote, which will of course be nothing.

myfile<<"test1 writing files"<<" ";
myfile.flush(); 
myfile.seekg(0, ios_base::beg);
myfile>>str1;

seekg is used to change the position you read (get) from the file. seekp is used to change the position you write (put) to the file.



来源:https://stackoverflow.com/questions/35836214/why-i-cant-read-from-file-using-file-ptrvariable-in-my-program

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