Oliver Liu
Oliver Liu

Reputation: 19

How to output content in multiple (.txt) files

I created a program that can take an integer as its input from a file and generate multiplication tables from 1 up to that integer read from the file. For example, if the program reads (3) from the file, it will output:

1*1 = 1
1*2 = 2
... up to
1*10 = 10
and then 
2*1 = 1 
.....
2*10 = 10
and so on up to three suppose that the number read from the file is 3
3*1 = 1
....
3*10 = 30

Now, I am trying to output each multiplication tables in different (.txt) files where for example table1.txt would contain 1*1 = 1 .... up to 1*10 = 10 and table2.txt would contain 2*1 = 2 .... up to 2*10 = 10 and the same procedure for table3.txt.

I can only create one file that only contains the first multiplication table and I do not know how to display the rest of the tables in different files.

I would really appreciate any help or insights to solve this problem. Thank you!

This is what I have:

#include <iostream>
#include <fstream>

using namespace std;

int main ()
{
    int num, a, b;
    fstream inputStream;
    ofstream outputStream;

    inputStream.open("input.txt"); //let's say input.txt holds the number 3

    while (inputStream >> num)
    outputStream.open("table.txt");

    for (a = 1; a <= num; a++) 
    {
        for (b = 1; b <= 10; b++)
        {
            outputStream << a << " X "
                   << b << " = "
                   << a*b << endl;
        }
        inputStream.close();
        outputStream.close();
    }                  
    return 0;
}

Upvotes: 1

Views: 4536

Answers (1)

POTEMKINDX
POTEMKINDX

Reputation: 395

#include <iostream>
#include <string>
#include <fstream>

int main(void) {
    const int Count = 10;              //Count of files
    std::string name = "example_";     //base pattern of file name
    std::ofstream outfstr[Count];      //creating array of 10 output file streams
    for(int i = 0; i < Count; ++i) {   //open all file streams 
        outfstr[i].open(name + char('0' + i) + ".txt");
    }

    for(int i = 0; i < Count; ++i) { // write value of i to i-th stream
         outfstr[i] << "Some rezult " << i;
    }
    return 0;
}

Upvotes: 1

Related Questions