我怎样才能在C ++中自动打开某些文件

How can i open certain file's automatically in c++

我尝试在 C++ 中自动打开某些文件。文件的标题相同,只是文件编号不同。

like this ' 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;
}`

现在,函数 'Form' 不起作用。我没有别的想法。 如果您有任何意见或想法,请告诉我。 谢谢!

您的代码中有几个问题。
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;
    }

*我没有测试代码,但如果我没有忽略一些愚蠢的东西,它应该可以工作。