如何使用C ++写入文件的特定列?

时间:2011-11-24 19:56:55

标签: c++ string file ofstream

使用C ++,我想生成一个文件,我必须在每行的末尾添加行号。有些行在第13个字符后结束,其中一些在第32个字符后结束。但是行号应该在最后。一行是80个字符长,该行的最后一个数字应该在该行的第80列。

有没有办法实现这个目标?我使用ofstream初始化我的文件,使用C ++。

2 个答案:

答案 0 :(得分:1)

嗯,这是使用字符串流的一种方法:

#include <iostream>
#include <iomanip>
#include <sstream>

using namespace std;

int main() {
    int lineNum = 42;
    stringstream ss;
    ss << setw(80) << lineNum;
    ss.seekp(0);
    ss << "information for beginning of line";
    cout << ss.str() << endl;
    return 0;
}

基本上将流设置为右对齐并填充到80个字符,放下行号,然后搜索到可以输出任何所需内容的行的开头。如果您继续在流中写入一长串数据,那么您当然会覆盖您的行号。

答案 1 :(得分:1)

填充每个输出行:

#include <sstream>
#include <string>
#include <iostream>

void
pad (std::string &line, unsigned int no, unsigned int len = 80)
{
  std::ostringstream n;

  n << no;

  line.resize (len - n.str().size (), ' ');
  line += n.str();
}

int
main ()
{
  std::string s ("some line");

  pad (s, 42, 80);
  std::cout << s << std::endl;
  return 0;
}