在 c++ 中将数据写入文件时奇怪的初始空白空间

Strange initial empty space writing data into a file in c++

本文关键字:空间 空白 文件 c++ 数据      更新时间:2023-10-16

我的应用程序遇到了一个奇怪的问题,尽管我尝试了几种解决方案,但没有一种解决方案解决了我的问题。

我的 c++ 应用程序生成一组包含自定义数据的文件。到目前为止,代码似乎工作正常,并且文件已正确生成,除了第一个。文件的预期格式如下:

@Header
@Line1E1,Line1E2,Line1E3
@Line2E1,Line2E2,Line1E3

但是,我注意到第一个生成的文件(并且只有第一个)的第一行有一个奇怪的空白区域:

   @Header
@Line1E1,Line1E2,Line1E3
@Line2E1,Line2E2,Line1E3

由于所有文件的代码都相同,我想知道它出了什么问题,但到目前为止,我还没有能够检测到问题的根源。

以下是我的代码的简化版本:

/* Variables */
std::ofstream Fil;
std::stringstream ss;
ss.precision (10);
ss.width (10);
ss.setf (ios::fixed);
for (int Inx = 0; Inx < MaxInx; Inx++) {
  sprintf (FilNam, "%i-ExportFile.txt", Inx);
  Fil.open(std::string (FilNam).c_str (), std::ofstream::out);
  SavSta = Fil.is_open ();
  if (SavSta) {
    ss << "@Header"        << "n";
    ss << "@Matrix name: " << MtxName  << "n";
    ss << /* Matrix data goes here */ << "n";
    Fil << ss.rdbuf ();
    ss.str(std::string ());
    ss.clear ();
  }
  Fil.close ();
}

它来自:

ss.width(10);

从 cplusplus.com

如果制图表达的标准宽度短于字段宽度,则表示法将使用填充字符填充

只需删除它,您就会没事的。