我如何在C++中自动打开某个文件
我试图在C++中自动打开某个文件。文件的标题是相同的,但只有不同的文件号码。我如何在C++中自动打开某个文件
这样的 'test_1.txt test_3.txt test_6.txt ......'
这些数字不能以普通的先后顺序。
这里是我的代码
`
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main(){
int n[20]= {4,7,10,13,16,19,21,24,27,30,33,36,39,42,45,48,51,54,57,60};
ifstream fp;
ofstream fo;
fp.open(Form("test%d.txt",n));
char line[200];
if(fp == NULL)
{
cout << "No file" << endl;
return 0;
}
if(fp.is_open())
{
ofstream fout("c_text%d.txt",n);
while (fp.getline(line, sizeof(line)))
{
if(line[4] == '2' && line[6] == '4')
{
fout<<line<<"\n";
}
}
fout.close();
}
fp.close();
return 0;
}`
现在,函数 '形式' 是行不通的。我没有别的想法。 如果您有任何意见或想法,请告诉我。 谢谢!
你的代码有几个问题。
1.如您所说,您的文件名为test_NR.txt,但您正在尝试打开testNR.txt。所以你错过了_
2. fp.open(Form("test_%d.txt", n[i]);
应该工作。你无法引用整个数组,你必须指出一个具体的值。
3.如果您想要逐个打开所有文件,则必须在循环中包围代码。
例子:
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main(){
int n[20]= {4,7,10,13,16,19,21,24,27,30,33,36,39,42,45,48,51,54,57,60};
ifstream fp;
ofstream fo;
for(int i=0; i<sizeof(n); i++)
{
fp.open(Form("test_%d.txt",n[i]));
char line[200];
if(fp == NULL)
{
cout << "No file" << endl;
return 0;
}
if(fp.is_open())
{
ofstream fout("c_text%d.txt",n[i]);
while (fp.getline(line, sizeof(line)))
{
if(line[4] == '2' && line[6] == '4')
{
fout<<line<<"\n";
}
}
fout.close();
}
fp.close();
}
return 0;
}
*我没有测试的代码,但如果我没有忽视一些愚蠢的事,它应该工作。
什么是Form()? –
Form()是'ROOT'函数。我很抱歉想解释。 –
使用'std :: stringstream'从模板和计数器中创建字符串。 – Barmar