How to add something to a file line by line in C ++?

Let's consider that I have this .txt file:

one
two
three

And how to make such a file from this:

<s> one </s> (1)
<s> one </s> (2)
<s> one </s> (3)
<s> two </s> (1)
<s> two </s> (2)
<s> two </s> (3)
<s> three </s> (1)
<s> three </s> (2)
<s> three </s> (3)

How can i do this?

+4
source share
1 answer

You can use stream iterators to first read your input file into std::vector, saving each line:

using inliner = std::istream_iterator<Line>;

std::vector<Line> lines{
    inliner(stream),
    inliner() // end-of-stream iterator
};

With the structure of the Lineannouncement is necessary operator>>based on std::getline:

struct Line
{
    std::string content;

    friend std::istream& operator>>(std::istream& is, Line& line)
    {
        return std::getline(is, line.content);
    }
};

Working example:

#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>

struct Line
{
    std::string content;

    friend std::istream& operator>>(std::istream& is, Line& line)
    {
        return std::getline(is, line.content);
    }
};

int main()
{
    std::istringstream stream("one\ntwo\nthree");

    using inliner = std::istream_iterator<Line>;

    std::vector<Line> lines{
        inliner(stream),
        inliner()
    };

    for(auto& line : lines)
    {
        int i = 1;
        std::cout << "<s> " << line.content << " </s> (" << i << ")" << std::endl;
    }
}

To complete your work, change the line stream for the file stream and output the completed result to a file.

0
source

Source: https://habr.com/ru/post/1659023/


All Articles