Problems printing in the arcihvo.txt

0

Help My program only creates the empty file.txt, could you help me to make the data that you enter in it be saved in the file.

void agregar(){
    system("cls");
    system ("color 3e");

    fflush(stdin);
    printf("\n%d.Nombre de contacto:  ", (cont+1));
    gets(control[cont].nom);//getline (cin,nom)

    fflush(stdin);
    cout<<"\nApellido de contacto:  ", (cont+1);
    gets(control[cont].ap);

    fflush(stdin);
    cout<<"\nTelofono:  ";
    scanf("%d", &control[cont].tel);

    fflush(stdin);
    cout<<"\nDirecci2n:  ";
    gets(control[cont].dir);

    fflush(stdin);
    cout<<"\nDepartamento:  ";
    gets(control[cont].dep);

    cont++;

}


void escribir ()
    {
    ofstream archivo;

    archivo.open("guia telefonica.txt",ios::out);//abrir el archivo


    archivo.close();//cerrar el archivo
}
    
asked by Hilario Jose Quevedo Palma 09.11.2018 в 01:22
source

2 answers

1
  

Help My program only creates the empty file.txt

I do not know what you expected the file to have if, literally, all you do is open it and then close it:

void escribir ()
    {
    ofstream archivo;

    archivo.open("guia telefonica.txt",ios::out);//abrir el archivo


    archivo.close();//cerrar el archivo
}

I suggest you write things in the file, so it will not be empty:

void escribir ()
{
    using namespace std;

    if (ofstream archivo{"guia telefonica.txt"})
    {
        archivo << "Datos, datos, datos!\n";
    }
}

As you can see I have not called std::ofstream::close , this is because it is automatically called when leaving the function since that class follows the RAII pattern .

    
answered by 09.11.2018 в 10:53
0

Once the file is opened, all you have to do is add data using the operator << . Same as you would with cin . In this page you have the ofstream reference.

    
answered by 09.11.2018 в 11:06