(C++) How to make a program write to 2 different files?

Asked

Viewed 66 times

-3

I made 2 attempts, the first one is error, and the second one does not write. could help me?

#include<iostream>
#include<fstream>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<cstdlib>
using namespace std;
int main()
{
    string linha;
    fstream fin ("ex2.txt");
    ofstream fout("ex2par.txt");
    ofstream fout("ex2impar.txt");
    if(fin.is_open())
    {
        while(getline(fin,linha))
        {
            int num = atoi(linha.c_str());
            if (num%2 == 0)
            {
                cout << "par " << num << endl;
                fout.open("ex2par.txt",ios::app);
            }
            else
            {
                cout << "impar " << num << endl;
                fout.open("ex2impar.txt",ios::app);
            }

        }
    }
}
/*int main()
{
    string linha;
    fstream fin("ex2.txt");
    ofstream par("ex2par.txt");
    ofstream impar("ex2impar.txt");
    if(fin.is_open())
    {
        while(getline(fin,linha))
        {
            int num = atoi(linha.c_str());
            if (num%2 == 0)
            {

                cout << "par " << num << endl;
                par.open("ex2par.txt");
            }
            else
            {

               cout << "impar " << num << endl;
                impar.open("ex2par.txt");
            }
        }

    }
}*/
  • But the messages you’re sending all to cout. At what point did you really try to write the texts we files?

  • I did not understand very well, in case it would not be in the declared ofstream par("ex2par.txt"); and the odd ofstream("ex2impar.txt");, because I tried both with FOUT but gave error, as in the commented part

1 answer

0


Good night.

On the part not commented:

you have created 2 variables with the same name fout. If vc. call the second of fout2 for example will not give error. When vc. initializes the streams with the filenames they will already open. You can take the open commands. To write to the files use the variables of the corresponding streams and not Cout. For example: fout << "par" << Endl; See if the following code helps you:

int main()

{

    string linha;

    fstream fin ("ex2.txt");

    ofstream fout("ex2par.txt");

    ofstream fout2("ex2impar.txt");

    if(fin.is_open())

    {
        while(getline(fin,linha))

        {

            int num = atoi(linha.c_str());

            if (num%2 == 0)

            {

                fout << "par " << num << endl;

            }

            else

            {

                fout2 << "impar " << num << endl;

            }


        }

    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.