-1

我正在尝试在 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;
}`

现在,函数“表单”不起作用。我没有其他想法。如果您有任何意见或想法,请告诉我。谢谢!

4

1 回答 1

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

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

于 2017-06-01T06:18:54.167 回答