简体   繁体   English

为什么在程序中无法使用“ file_ptr >>变量”从文件读取?

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

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? 为什么即使将“ test1 Writing files”写入文件,控制台上也没有任何输出?

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). 将需要同时打开文件以进行读取和写入(对不起,请忽略;默认情况下,同时打开fstream进行读取和写入操作)。 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. 写入(并刷新输出)之后,您将需要seekg()返回文件的开头,或者您将尝试读取最后编写的内容之后的内容,这当然没什么。

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. seekg用于更改从文件读取(获取)的位置。 seekp is used to change the position you write (put) to the file. seekp用于更改您写入(放置)到文件的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我无法让我的程序在函数中读取我的文件 - I can't get my program to read my file in a function 我无法让程序正确读取输入文件中的值(2D数组) - I can't get my program to read the values from my input file correctly (2D array) 为什么我的程序无法从C ++中的二进制文件读取数据? - Why my program doesn't read data from the binary file in C++? 为什么我不能从文件中读取一行 - Why can't I read a line from file 为什么在使用 ofstream 变量向文件添加一些信息后,无法将文件中的数据写入字符串? - Why I can't write data from a file to a string, after I added some information to file using an ofstream variable? 为什么我不能传递对我的 unique_ptr 的引用? - why can't i pass a reference to my unique_ptr? 我无法从文件中读取 - I can't read from a file 为什么我的C ++程序只能读取绝对目录,而不能读取同一文件夹中的文件? - Why my C++ program can only read absolute directory but not file in the same file folder? 我似乎无法弄清楚为什么我对文件的读/写功能不起作用 - I can't seem to figure out why my read/write to a file functions are not working 为什么我不能用Code :: Blocks C ++读取文件? - Why can't I read a file with Code::Blocks C++?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM