【问题标题】:C++ Writing a file inside a loop [closed]C ++在循环内编写文件[关闭]
【发布时间】:2014-12-29 19:14:09
【问题描述】:

这应该将 30 秒倒计时到一个 txt 文件中。但它也几乎从不制作 txt 本身。我究竟做错了什么?还是循环中的c ++只是不具备文件处理能力。 文本文件中没有任何内容

for (i = 30; i >= 0; i--)
    {
        ofstream file;
        file.open("asd.txt");
        file << i;
        file.close();
        Sleep(1000);
    }

【问题讨论】:

  • “但它也几乎不会生成 txt 本身”这是什么意思?
  • 你是说你只得到0 作为文件中的文本吗?那是因为你没有处于附加模式;将开放模式std::ios_base::app 添加到open
  • 我希望 txt 覆盖自己
  • 您的循环将运行约 31 秒,而不是约 30 秒。
  • @PeterM close() 将在内部刷新。

标签: c++ file loops filestream ofstream


【解决方案1】:

基本上,您每次都会创建代表文件的对象并尝试打开它。 如果您每次使用新引用(对象)访问文件,它会写入新数据并删除以前的数据。 尝试这样做:

int main()
{
    ofstream file;
    file.open("test.txt");
    for (int i = 30; i > 0; --i)
    {
        file << i << endl;
        Sleep(1000);
    }
    file.close();


    system("pause");
    return 0;
}

【讨论】:

    【解决方案2】:

    像这样将 ofstream 移出循环:

    // ^^ There is the useless stuff
    ofstream file;
    for (i=0;i<maxs;i++)
    {
        system("cls");
        secondsLeft=maxs-i;
        hours=secondsLeft/3600;
        secondsLeft=secondsLeft-hours*3600;
        minutes=secondsLeft/60;
        secondsLeft=secondsLeft-minutes*60;
        seconds=secondsLeft;
        cout << hours<< " : " << minutes<< " : " << seconds << " ";
        file.open ("countdown.txt", ios::trunc);
        file << hours << " : "  << minutes<< " : " << seconds;
        file.close();
        Sleep(1000);
    }
    

    【讨论】:

    • 大声笑,它很有效:D
    【解决方案3】:

    您可以声明ofstream 退出循环。

    如果你必须在循环中使用它,请使用附加模式。

    file.open("test.txt", std::ofstream::out | std::ofstream::app);
    

    【讨论】:

      【解决方案4】:

      首先,您将在每个循环中覆盖您的输出文件“asd.txt”。您只需要为每个将执行 IO 的会话(在循环外)创建和初始化一个文件指针。关闭文件指针也是如此。

      ofstream file;    //Create file pointer variable
      file.open("asd.txt");    //Initialize 'file" to open "asd.txt" for writing
      for (i = 30; i >= 0; i--)
        {
         file << i;   //You'll need to add a new line if you want 1 number per line
         Sleep(1000);  //Assuming this is in microseconds so sleep for 1 second
        }
      file.close();   //close the file pointer and flushing all pending IO operations to it.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-07
        • 2012-01-02
        • 2020-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多