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

标签 c++ file stringstream

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

我的 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

If the standard width of the representation is shorter than the field width, the representation is padded with fill characters

只要删除它就可以了。

关于c++ - 奇怪的初始空白空间将数据写入c++中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29093845/

相关文章:

c++ - 将 FFTW 库添加到 QT 项目中

c - 将 .txt 读入矩阵

python - 使用 blobstore 处理程序获取上传文件的链接

javascript - spring 3.0 web mvc中找不到JS和CSS文件错误

c++ - 多次提取和插入时奇怪的字符串流行为。

c++ - 删除小部件后qt调整窗口大小

c++ - 我可以将具有非常量值类型的映射转换为具有常量值类型的映射吗?

C++ 使用 vector 从文本文件中读取和写入数字

C++:如何构建两个空格分隔字符串的交集字符串?

c++ - 防止为字符串流提取运算符 (>>) 不支持的类型实例化模板类