【问题标题】:ofstream:- no output on the text file though the file is getting createdofstream:- 尽管正在创建文件,但文本文件上没有输出
【发布时间】:2017-10-02 08:17:11
【问题描述】:
    void megaadmin()
    {
        system("cls");
        cout<<"this console is only for registering new admins";
        cout<<"please enter the required username";
        string temporary_string;
        cin>>temporary_string;
        ofstream f("admin_details.txt",ios::out|ios::app);
        f<<temporary_string;
        cout<<"please enter the password";
        cin>>temporary_string;
        f<<temporary_string;
        cout<<"would u like to enter more usernames and passwords if yes enter 1 eles 2";
        int n;
        cin>>n;
        if(n==1)
            megaadmin();
        else
            exit(0);
    }

admin_details.txt 正在创建,但我输入的用户名和密码信息并未存储在该特定文本文件中

【问题讨论】:

  • 何时以及如何检查文件的内容?也许您应该在检查之前flush 缓冲区?
  • 另外(但与您的问题无关),我建议您在显示的代码中使用 loops 而不是递归。
  • 同样不相关:在 ofstream 上指定 ios::out 毫无意义。
  • @Someprogrammerdude 我是 C++ 新手,我该如何刷新这段代码?
  • @varunkrishna 使用ostream::flush()。例如,f.flush()

标签: c++ string c++14 fstream ofstream


【解决方案1】:

在每个cin &gt;&gt; temporary_string; 之后我会添加cout &lt;&lt; temporary_string 仅用于调试以确保成功读取字符串。

如果是,则没有输出,因为您的流可能未刷新。 只需拨打f.flush() 即可看到内容。

顺便说一句,当你关闭程序时,流也会在销毁过程中被刷新,所以你也会看到内容。

【讨论】:

  • 我不完全理解flush,但我确实flush仍然无法正常工作,但我最近用一些ofstream制作了另一个代码,它工作得非常好我不知道为什么这个不工作
  • 检查 this 以查看正在刷新的内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
  • 2017-08-10
相关资源
最近更新 更多