创建并写入N个文本文件 [英] Create and write in N number of textfiles
问题描述
我的任务是创建一个程序,该程序将从文本文件中读取数字N并创建乘法表,最多为N.每个乘法表将被写入单独的单独文件中。该程序基本上会为文本文件创建N编号。
例如Table1.txt将包含
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
Table2.txt将包含
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
等等
到目前为止,我的代码看起来像这样,只会将所有乘法表打印成一个文本文件。
My assignment is to create a program that would read a number N from a textfile and create multiplication table up to N. Each multiplication table is to be written into separate a separate file. The program would essentially create N number for textfiles.
For example Table1.txt would contain
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
Table2.txt would include
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
and so on
So far my code looks like this and will only print all the multiplication tables into one textfile.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//initializations
int input, product;
ifstream inputstream;
ofstream outputstream;
inputstream.open("input.txt");
outputstream.open("output.txt");
//Inputting the number from the text file.
inputstream >> input;
//Creating the multiplication tables
for (int counter = 1; counter <= input; counter++)
{
for (int counter2 = 1; counter2 <= input; counter2++)
{
product = counter * counter2;
outputstream << counter << " x " << counter2 << " = " << product << endl;
}
outputstream << "==========================================" << endl << "==========================================" << endl;
}
return 0;
}
我应该如何更改代码以获得作业要求的内容?我的初步猜测是将output.open(output.txt)放入循环中,但是当我这样做时,我只能得到一个具有1次表的文本文件,即使输入文件中的数字是10 。
How should I change my code to get what the assignment is asking for? My intial guess was to put the output.open("output.txt") into the loop but when I did that I was only able to get one text file which had the 1's times table even though the number in my input file was 10.
for (int counter = 1; counter <= input; counter++)
{
outputstream.open("output.txt");
for (int counter2 = 1; counter2 <= input; counter2++)
{
product = counter * counter2;
outputstream << counter << " x " << counter2 << " = " << product << endl;
}
outputstream << "==========================================" << endl << "==========================================" << endl;
}
推荐答案
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
ostringstream filename;
for (int i=0; i<10; i++)
{
filename.str("");
filename << "Table" << i << ".txt";
cout << filename.str() << endl;
}
return 0;
}
输出
Output
Table0.txt
Table1.txt
Table2.txt
Table3.txt
Table4.txt
Table5.txt
Table6.txt
Table7.txt
Table8.txt
Table9.txt
这篇关于创建并写入N个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!