-1

I'm try to open certain file automatically in c++. File's title is same but only different file's number.

like this ' test_1.txt test_3.txt test_6.txt ... '

These numbers are not listed in regular sequence.

And here is my code

`

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

Now, Function 'Form' doesn't work. and I don't have another idea. If you have any comment or idea, please tell me. Thank you!

orde.r
  • 521
  • 2
  • 5
  • 13

1 Answers1

0

You have several problems in your code.
1. As you told us, your files are called test_NR.txt, but you are trying to open testNR.txt. So you are missinge the _
2. fp.open(Form("test_%d.txt", n[i]); should work. You cant refere to an entire array, you have to point out one specific value.
3. If you want to open all the files one by another, you have to surround your code in an loop.

Example:

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

*I didn't test the code but if I didnt overlook something stupid, it should work.

xMutzelx
  • 566
  • 8
  • 22