0

So, I wonder if there's a good way to save and retrieve user input data from a file. I want to retrieve variables that are string arrays, int, and double. I know that getline is commonly used but doesn't work with int and double. Any advice or tips on what I could use to make it work with int and double variables?

I have been trying to research it, but I don't know if I understand it correctly.

BuckyE
  • 1
  • 3
  • One way is to convert everything to a string. Then, write this to the file as a C-style string (you can't write out a `std::string` directly). – Paul Sanders Jun 22 '21 at 00:38
  • @PaulSanders are there any good reads that might help me understand how to do that better? I am quite new to c++ – BuckyE Jun 22 '21 at 00:42
  • You might read [this](https://isocpp.org/wiki/faq/serialization) (found by Googling `C++ serialization`). – Paul Sanders Jun 22 '21 at 00:44
  • Does this answer your question? [Is it possible to serialize and deserialize a class in C++?](https://stackoverflow.com/questions/234724/is-it-possible-to-serialize-and-deserialize-a-class-in-c) – prehistoricpenguin Jun 22 '21 at 01:25

1 Answers1

0

A good way to save and retrieve user data from a file is by using classes, as in the example below (I'm sorry for the comments Portuguese):

//Gravando objetos em arquivos

#include <iostream>
#include <fstream> //ofstream e ifstream
using namespace std;

class Pessoa
{
private:
    string nome;
    int idade;

public:
    string& getNome() //obter nome
    {
        return nome;
    }
    int getIdade() //obter idade
    {
        return idade;
    }

    void setNome(string& nome)
    {
        this->nome = nome;
    }

    void setIdade(int idade)
    {
        this->idade = idade;
    }

    //sobrecarga do operador de inserção de dados <<
    //ostream = output stream
    friend ostream& operator<<(ostream& os, const Pessoa p)
    {
        //escrever cada membro
        os << "\n" << p.nome << "\n";
        os << p.idade;
        return os;
    }

    //sobrecarga do operador de extracao de dados >>
    //istream = input stream
    friend istream& operator>>(istream& is, Pessoa& p)
    {
        //ler cada membro
        is >> p.nome >> p.idade;
        return is;
    }
};

char menu()
{
    char resp;

    cout << "Digite 1 para inserir pessoas\n";
    cout << "Digite 2 para listar as pessoas\n";
    cout << "Digite 0 para sair\n";
    cout << "Opcao: ";
    cin >> resp;
    return resp;
}

int main(int argc, char *argv[])
{
    char resp; //resposta

    while(true) //loop infinito
    {
        resp = menu();
        if(resp == '1')
        {
            Pessoa pessoa;
            string nome;
            int idade;

            //abrir arquivo
            ofstream ofs("arquivo.txt", fstream::app); //esse fstream::app eh de append, q eh pra adicionar ao final do arquivo

            cout << "\nDigite o nome da pessoa: ";
            cin >> nome;
            cout << "Digite a idade da pessoa: ";
            cin >> idade;
            cout << endl;

            //seta o nome da pessoa
            pessoa.setNome(nome);
            pessoa.setIdade(idade);

            ofs << pessoa; //assim daria erro se nos nao sobrecarregassemos o operador

            //fechar arquivo
            ofs.close();
        }
        else if(resp == '2')
        {
            Pessoa p;
            ifstream ifs("arquivo.txt");

            cout << "\nListando pessoas...\n\n";

            //verifica se o arquivo existe e se eh possivel o ler
            if(ifs.good())
            {
                // eof == end of file
                // enquanto n chegar no fim do arquivo
                while(!ifs.eof())
                {
                    ifs >> p; //n da certo se n sobrecarregar tbm / faz a extracao dos dados

                    //mostrar os dados
                    cout << "Nome: " << p.getNome() << "\n";
                    cout << "Idade: " << p.getIdade() << "\n\n";
                }
                ifs.close();
            }
            else
            {
                cout << "Falha ao abrir o arquivo!\n\n";
            }
        }
        else if(resp == '0')
        {
            cout << "\nBye!\n";
            break;
        }
        else
        {
            cout << "\nOpcao invalida. Tente novamente...\n\n";
        }
    }

    return 0;
}

About getline() does not work with int and double, this happens because getline() only reads string.

JMBCODE
  • 15
  • 6