-1

I am trying to read in integers from a .txt file. The file has 2048 lines, and each line is an integer. The file starts like this:

   0
   0
   0
   0
   0
   0
   0
   0
   0
   0
   0
   0
   0
   0
   0
   0
   0
  15
  66
  53
  47
  53
  63

I want to read in this data, then print out the number on the nth line n times to a new file. For example, the number on line 0 is 0, so I would output 0 zero times to the new file, etc. And the number 15 is on line 18, so I would output 15: 18 times to a new file. I want to apply this procedure to the whole file. Normally, I would just copy and paste my whole .txt file into a c++ compiler that allows pasting multiple lines of input for the following program:

#include <iostream>
int main() {
int x;
for (int j=1; j<2048; j++)
{
    std::cin >> x;
    for (int k=0; k<x; k++)
    std::cout << j << std::endl;
}
return 0;}

I was wondering if there is a way to read in the input from the file with the data, apply the above method, and then output the result into a different .txt file.

  • [Read](https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c), [parse](https://stackoverflow.com/questions/4442658/c-parse-int-from-string) then [write](https://stackoverflow.com/questions/2393345/how-to-append-text-to-a-text-file-in-c) – Martheen Oct 23 '20 at 03:17

1 Answers1

0

Ah ok, thanks Martheen, the answer to my problem is the following:

#include <iostream>
#include <fstream>

int main() {
    ifstream infile("comptest.txt");
    ofstream outfile("newcompttest.txt");
    int a;
    int j=1;
while (infile >> a)
{
    for (int k=0; k<a; k++)
    {
    outfile << j << std::endl;
    }
   j++;
}
infile.close();
        return 0;
}