简体   繁体   中英

Reading in integer txt file C++ and writing to another txt file

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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