Save data to files

2

I need to be able to save several data in a .txt

But I do not know how to do it because at the moment of saving it I keep symbols and not what I want

Here's how: fprintf (archivo, "%s", cliente, "%d", apartamento, "%d", npiso)

cliente is a string

apartamento and npiso are int

    
asked by WILSON ESTEBAN MARTINEZ TORRES 10.11.2016 в 01:07
source

2 answers

1

Is being used incorrectly fprintf

fprintf (archivo, "%s", cliente, "%d", apartamento, "%d", npiso)

should be used as follows:

fprintf (archivo, "%s%d%d", cliente, apartamento, npiso)

That is, you have to place all the print formats in the second parameter, and then place the corresponding variables.

    
answered by 10.11.2016 в 01:36
1

Use.

The fprintf function is part of the C libraries adapted to C ++ and resides in the header <cstdio> , the signature of the function is as follows:

int fprintf( std::FILE* archivo, const char* formato, ... );
  • The archivo parameter must be a file handler pointer ( std::FILE* ) which is obtained through the fopen , do not forget to close the file with fclose .
  • The formato parameter is a text string with different format specifiers.
  • The parameters in ... will be a comma-separated list of the data that must match the format specifiers.

Therefore, as you mentioned Monpeco , the use you should give to fprintf should be :

archivo = std::fopen("mi_archivo.txt", "w");
...
...
std::fprintf(archivo, "%s%d%d", cliente, apartamento, npiso);

Problem.

  

If that's the way I've done it and it's still the same

It is very likely that the variable cliente does not have valid data and it is these that will end up in your file as symbols .

Proposal.

Forget about fprintf , use the C ++ stream library:

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::string cliente{};
    int apartamento{}, npiso{};

    std::cout << "Cliente: ";
    std::cin >> cliente;

    std::cout << "\nApartamento: ";
    std::cin >> apartamento;

    std::cout << "\nPiso: ";
    std::cin >> npiso;

    std::ofstream archivo("mi_archivo.txt");
    archivo << cliente << '\n' << apartamento << '\n' << npiso << '\n';

    return 0;
}
    
answered by 10.11.2016 в 09:27