C++ reading multiple input files sequentially

2019-07-28 18:46发布

I have 47 different files:

  • 001_template.dat
  • ...
  • 047_template.dat

in a directory called /data. I need to compare each of these template files to three different query files, also in the directory. These are named:

  • 001_AU01_query.dat
  • 001_AU12_query.dat
  • 001_AU17_query.dat.

I know how to get all of this to run, but I will have to cut and paste these 6 lines of code 46 more times and the program will get very long and confusing.

Is there a good way to loop over these files? Possibly by looping over the template files and then doing three queries for every template? I obviously have a similarity function and a sort function already defined, as well as inputFile. Here is the code I would like to convert: (not homework this is for a facial expression recognition project I have been working on)

int main()
{
vector<float> temp01;
vector<float> temp12;
vector<float> temp17;

temp01 = similar(inputFile("data/001_AU01_query.dat"), inputFile("data/001_template.dat"));
sortAndOutput(temp01);
temp12 = similar(inputFile("data/001_AU12_query.dat"), inputFile("data/001_template.dat"));
sortAndOutput(temp12);
temp17 = similar(inputFile("data/001_AU17_query.dat"), inputFile("data/001_template.dat"));
sortAndOutput(temp17);

}

标签: c++ c input vector
3条回答
孤傲高冷的网名
2楼-- · 2019-07-28 19:17

Use two arrays holding the names of files and templates and loop on them:

char* files[47] = {"file1", "file2", ...., "file47"};
char* templates[3] = {"template1", "template2", "template3"};

and loop on them:

for(i=0; i<47; i++){
  for{j=0; j<3; j++){
    compare(file[i],template[j]);
  }
}
查看更多
该账号已被封号
3楼-- · 2019-07-28 19:24
void work()
{


vector<float> temp;

char data[100];
char templates[100];
char* datas[3] = { "data/%03d_AU01_query.dat", "data/%03d_AU12_query.dat", "data/%03d_AU17_query.dat" };
for (int i = 1; i < 48; i++)
{
    for(int j = 0; j < 3; j++)
    {
        sprintf_s(templates, "data/%03d_template.dat", i);   // create the name of the template 1-47
        sprintf_s(data, datas[j], i);
        temp01 = similar(inputFile(data), inputFile(templates));
        sortAndOutput(temp);
    }
}
}
查看更多
贪生不怕死
4楼-- · 2019-07-28 19:30

Then I would go with creating the file names with sprintf into the loop:

char data[100];
char template[100];
char* datas[3] = {"%3d_AU01_query.dat", "%3d_AU12_query.dat", "%3d_AU17_query.dat"};
for(i=0; i<47; i++){
  for{j=0; j<3; j++){
    sprintf(template, "%03d_template.dat", i);   // create the name of the template 1-47
    sprintf(data, datas[j], i);
    compare(template, data);
  }
}

That should work as expected I think.

查看更多
登录 后发表回答