Reputation: 19
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: 0
Views: 289
Reputation: 633
You should create new file for an every single loop iteration:
#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
inputStream >> num;
inputStream.close();
for (a = 1; a <= num; a++)
{
outputStream.open("table" + std::to_string(a) + ".txt");
for (b = 1; b <= 10; b++)
{
outputStream << a << " X "
<< b << " = "
<< a*b << endl;
}
outputStream.close();
}
return 0;
}
Note, that you should build your code with -std=c++11 flag, because of std::to_string method. This code generates you num files(tablenum.txt), each with multiplication table for specific number.
Upvotes: 1