简体   繁体   English

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

[英]How to write into specific columns of a file using C++?

Using C++, I want to generate a file in which I have to add the line number to the end of each line. 使用C ++,我想生成一个文件,我必须在每行的末尾添加行号。 Some lines end after 13th character, some of them end after 32nd. 有些行在第13个字符后结束,其中一些在第32个字符后结束。 But the line numbers should be in the end. 但是行号应该在最后。 A line is 80 characters long, the last number of the line should be in the 80th column of the line. 一行是80个字符长,该行的最后一个数字应该在该行的第80列。

Is there a way to accomplish this? 有没有办法实现这个目标? I initialize my file using ofstream, use C++. 我使用ofstream初始化我的文件,使用C ++。

Well, here's one way to go about it using a stringstream: 好吧,这是使用字符串流的一种方法:

#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;
}

Basically sets the stream to right align and pad to 80 chars, lays down your line number, and then seeks to the beginning of the line where you can output whatever you want. 基本上将流设置为右对齐并填充到80个字符,放下行号,然后搜索到行的开头,您可以输出任何您想要的内容。 If you keep writing a long line of data into the stream you'll overwrite your line number, of course. 如果你继续在流中写入一长串数据,你当然会覆盖你的行号。

Pad each output line: 填充每个输出行:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM