【问题标题】:C++ reading multiple input files sequentiallyC ++顺序读取多个输入文件
【发布时间】:2013-11-29 22:30:31
【问题描述】:

我有 47 个不同的文件:

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

在名为 /data 的目录中。我需要将这些模板文件中的每一个与目录中的三个不同的查询文件进行比较。这些被命名为:

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

我知道如何让所有这些运行起来,但是我必须再剪切和粘贴这 6 行代码 46 次,程序会变得非常冗长和混乱。

有没有循环遍历这些文件的好方法?可能是循环遍历模板文件,然后对每个模板执行三个查询?我显然已经定义了相似函数和排序函数,以及inputFile。这是我要转换的代码:(不是作业,这是我一直在做的面部表情识别项目)

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);

}

【问题讨论】:

  • 使用一个变量来保存文件名和这些文件的循环!您可以使用std::ostringstream 构造一个合适的字符串(打开文件时可能需要使用str.c_str())。
  • 多次复制和粘贴意味着您应该使用某种函数和/或某种循环
  • 也利用向量,因为您似乎知道如何使用它们。
  • 所以我可以使用字符串向量来保存文件名。嗯

标签: c++ c input vector


【解决方案1】:

然后我会在循环中使用 sprintf 创建文件名:

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);
  }
}

我认为这应该可以正常工作。

【讨论】:

  • 完美解决方案!谢谢!我也会在这里发布我的最终工作代码。
  • 很想得到积分,但好在它对你有用,祝你的代码好运:-)
【解决方案2】:

使用两个数组保存文件和模板的名称并循环它们:

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

然后循环:

for(i=0; i<47; i++){
  for{j=0; j<3; j++){
    compare(file[i],template[j]);
  }
}

【讨论】:

  • 这行得通!除了模板文件也会增加,所以 002_template 是匹配 002 查询时搜索的模板。所以这非常接近,它将所有模板文件按顺序与 001 查询进行比较。至少感谢您的开始!
【解决方案3】:
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);
    }
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多