Better way to copy a file and add commas?

I have been doing Project Euler problems lately and the one thing I've noticed a lot is they like using giant blocks of numbers in a lot of problems. I was going through each line and hitting comma, right arrow...this was a very slow process before I could even begin to start programming. I thought about it, I just got to number 13, and I was like there is no way I'm putting this many commas in, let's program. So I did, and this is what I came up with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <fstream>

int main() {
    std::ifstream input("input.txt");
    std::ofstream output("output.txt");

    if ((!input.is_open()) || (!output.is_open()))
        std::cout << "Failed to open files!\n";

    std::string copyLine;
    output << "{\n\t";
    while(!input.eof()) {
        getline(input, copyLine);
        output << "{";
        for (int i = 0; i < copyLine.length(); i ++) {
            if (i != copyLine.length() - 1)
                output << copyLine[i] << ",";
            else if (!input.eof())
                output << copyLine[i] << "},\n\t";
            else if (input.eof())
                output << copyLine[i] << "}};";
        }
    }

    return 0;
}


Sample input:
nnn
nnn
nnn

Sample output:
{
    {n,n,n},
    {n,n,n},
    {n,n,n}};

It's very simple, and I have a bunch of if statements in there because I like my arrays to be neat. Anyone have any improvements? This seemed to be the most effective way of doing anything like this. And yes, this particular program was for a two dimensional array.
Last edited on
I personally can't think of a better, more straight-forward solution in C++.
And I failed miserably trying to implement a buffered version, using std::ostringstream.

But you're not the first person to face such a problem, where you have to edit a file according to a pattern. Which is why tools like sed were invented, long ago.

http://gnuwin32.sourceforge.net/packages/sed.htm
http://en.wikipedia.org/wiki/Sed
I recall doing that sort of thing with emacs and it taking not a long time.

Edit: It took two rectangle inserts (M-x r t for the emacs unfamiliar - I know there a Vim equivalent) and ten seconds of typing to get an array of 50 strings that happily compiled.
Last edited on
It transformed this:
http://pastebin.com/RDrD3vkU

Into this:
http://pastebin.com/MtwCWQnX

In a matter of a tenth of a second. I was just wondering if there were more versatile ways to do something similar.

And Catfish, I've heard of Sed before, never used it, but used some programs that may have used it, or something like it. I believe Astyle is based off of Sed, if it doesn't use it.
Last edited on
Topic archived. No new replies allowed.