0

I'm wondering if anyone has any idea on how to take input from one file (.txt) and output it into multiple output files (.txt). For example if it read 3 integer values, it would output the first value to the first output file and so on. I'm curious just to see if I can save myself some time by not having to run an output function three different times.

Here's the code I've put together if anyone is interested to see further what I mean.

#include<iostream>
#include<fstream>
#include<string>
#include<array>
using namespace std;

int main()
{
ifstream instream;
ofstream outstream;
int ip;
string ipadd;
string name;
string date;
char test1;

instream.open("inputfile.txt");
outstream.open("ipaddress.csv");
outstream.open("name.csv");
outstream.open("date.csv");



if(instream.fail())
    cout<<"Incorrect File Name\n";


while(!instream.eof())
    {
                 instream>>ip;
                 if(ip==192)
                 {
                       instream.ignore(10000,'\n');
                 }
                 else
                 {
                 instream>>ipadd;
                 instream.ignore(3, ' - ');
                 instream>>name;
                 instream.ignore(2, '[');
                 instream>>date;
                 cout<<ip<<ipadd<<"   "<<name<<" "<<date<<endl;
                 outstream<<ipadd<<"  "<<name<<" "<<date<<endl;
                 instream.ignore(256,'\n');
                 }
    }

instream.close();
outstream.close();

        return 0;
}

The hope is to output the values ip & ipadd into one output file, the values stored in name into the second, and date into the third. For those curious, the program sorts through an Apache log and outputs the IP addresses, names, and login times of the user; excluding any from an internal network. I'm sure there are less than desirable practices I've put in, but thanks for taking the time to look at it.

1
  • 1
    If you want to output to 3 files, you need 3 ofstream variables. As it is, you open 3 files, but you immediately abandon 2 of them (or 2 of them fail, or something). Commented Jan 28, 2014 at 0:37

1 Answer 1

6

Create a separate ofstream for each file:

ofstream osIpAddress;
ofstream osName;
ofstream osDate;

Then handle each of them accordingly.

Sign up to request clarification or add additional context in comments.

1 Comment

That'll do it. Thanks for the response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.