我创建了一个程序,它可以从文件中取一个整数作为输入,并生成从1到从文件读取的整数的乘法表。例如,如果程序从文件中读取(3),它将输出:
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
现在,我试图输出不同(.txt)文件中的每个乘法表,例如table1.txt将包含1*1 = 1 .... up to 1*10 = 10
,table2.txt将包含2*1 = 2 .... up to 2*10 = 10
和table3的相同过程.TXT。
我只能创建一个只包含第一个乘法表的文件,而且我不知道如何在不同的文件中显示其余的表。
我非常感谢您解决此问题的任何帮助或见解。谢谢!
这就是我所拥有的:
#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;
}
答案 0 :(得分:1)
您应该为每个循环迭代创建新文件:
#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;
}
请注意,由于std :: to_string方法,您应该使用-std = c ++ 11标志构建代码。 此代码生成 num 文件(表 num .txt),每个文件都有特定数字的乘法表。