简体   繁体   中英

One input to multiple output files C++

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.

Create a separate ofstream for each file:

ofstream osIpAddress;
ofstream osName;
ofstream osDate;

Then handle each of them accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM