【问题标题】:fstream object is not reading data from the file?fstream 对象没有从文件中读取数据?
【发布时间】:2020-03-28 18:56:44
【问题描述】:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    fstream student;
    student.open("details.txt");
    string name,UID,sem;
    for(int i=0;i<5;i++)
    {
        cout<<"Enter the name , UID , semester\n";
        cin>>name>>UID>>sem;
        student<<name<<" "<<UID<<" "<<sem<<endl;
    }
string xyz;


while(getline(student,xyz))    
{

    cout<<xyz<<"\n";
}





student.close();



}

这显示错误,但如果我让 ifstream 对象写入和 ofstream 对象(与 ifstream 的对象不同)读取,那么只有它被执行。 谢谢你帮助我

【问题讨论】:

  • This shows error 显示什么错误?
  • 如果你想从文件中读取使用ifstream,如果你想写入文件使用ofstream。使用 fstream 只会让事情变得更复杂。
  • 这并没有解决问题,而是养成使用有意义的值初始化对象的习惯,而不是默认构造它们并立即覆盖它们。在这种情况下,这意味着将fstream student; student.open("details.txt"); 更改为fstream student("details.txt");。此外,您无需致电student.close();。析构函数会这样做。

标签: c++ file file-handling


【解决方案1】:

&lt;fstream&gt; 包含 ofstreamifstream 类。

您应该使用ofstream 对象将数据写入文件:

ofstream fileOut("file-name.txt");
fileOut << "data";
fileOut.close();

ifstream对象从文件中读取数据:

string data;
ifstream fileIn("file-name.txt");
fileIn >> data;
fileIn.close();

【讨论】:

  • 是的,如果我这样写它会起作用,但在什么情况下我可以使用 fstream?
  • 如何在这个程序中实现 fstream 可以请你帮我得到这个答案谢谢你的帮助
  • 您可以使用 fstream,但您必须指定您希望如何打开文件(用于读取或写入): fstream fs; fs.open ("file.txt", std::fstream::in); // 用于阅读; fs.open ("file.txt", std::fstream::out); // 用于写作; fs.close();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多