【问题标题】:Simple file writing with ostream_iterator creates file, but doesn't write使用 ostream_iterator 进行简单文件写入会创建文件,但不会写入
【发布时间】:2017-04-01 02:45:17
【问题描述】:

我有一个非常简单的代码来创建一个名为“Input.txt”的文本文件,并使用 ostream_iterator 写入它:

using namespace std;


int main()
{
    ofstream os{ "Input.txt" }; 
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++)
    {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);

    system("PAUSE");
    return 0;
}

上面的代码创建了一个“Input.txt”,但没有写入任何内容。我是否遗漏了一些非常明显和基本的东西?

【问题讨论】:

    标签: c++ file c++11


    【解决方案1】:

    在调用 system() 之前,您没有将流刷新到磁盘。

    您可以明确地flush()close() 流:

    int main() {
        ofstream os{ "Input.txt" };
        ostream_iterator<int> oo{ os,"," };
    
        vector<int> ints;
        for (int i = 0; i < 1000; i++) {
            ints.push_back(i);
        }
    
        unique_copy(ints.begin(), ints.end(), oo);
    
        os.close();
    
        system("PAUSE");
        return 0;
    }
    

    或者您可以在流周围放置范围大括号,以便它更快地超出范围。

    int main() {
        {
        ofstream os{ "Input.txt" };
        ostream_iterator<int> oo{ os,"," };
    
        vector<int> ints;
        for (int i = 0; i < 1000; i++) {
            ints.push_back(i);
        }
    
        unique_copy(ints.begin(), ints.end(), oo);
        }
    
        system("PAUSE");
        return 0;
    }
    

    【讨论】:

      【解决方案2】:

      我想通了,这是因为我在代码中有“System(“PAUSE”)”,阻止了输出流进入文件。这是工作代码:

      int main()
      {
          ofstream os{ "Input.txt" }; // output stream for file "to"
          ostream_iterator<int> oo{ os,"," };
      
          vector<int> ints;
          for (int i = 0; i < 1000; i++)
          {
              ints.push_back(i);
          }
      
          unique_copy(ints.begin(), ints.end(), oo);
          return 0;
      }
      

      不敢相信我错过了这个......

      【讨论】:

        猜你喜欢
        • 2016-09-25
        • 1970-01-01
        • 1970-01-01
        • 2015-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-03
        • 1970-01-01
        相关资源
        最近更新 更多