简体   繁体   中英

How to output different contents in various (.txt) files ( C++)

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

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(table num .txt), each with multiplication table for specific number.

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