0

I am doing a program that is supossed to save information of some classes. I am using ofstream and ifstream. Ofstream seems to be working properly as it creates one line for each attribute. This is the following .txt created by my ofstream function:

Audifonos
4.2
200
Water
10.4
12
Eggs
5.8
24

Attributes are declared as:

string name;
int cantidad;
float precio;

This is my ofstream function.

ofstream archivo("productos.txt", ios::out);
if(archivo.is_open())
{
    for(size_t i(0); i<arreglo.size(); i++)
    {
        Producto &p = arreglo[i];
        archivo << p.getName() <<endl;
        archivo << p.getPrecio() <<endl;
        archivo << p.getCantidad() <<endl;
    }
    archivo.close();
}

And this is my ifstream function.

ifstream archivo("productos.txt");
if(archivo.is_open())
{
    while(!archivo.eof())
    {
        string linea;
        Producto p;
        getline(archivo,linea);
        p.setName(linea);

        getline(archivo, linea);
        p.setPrecio(stof(linea));

        getline(archivo,linea);
        p.setCantidad(stoi(linea));


        if(archivo.eof())
        {
            break;
        }


        agregarp(p);
    }
}

Not a syntax problem, but I get this error when I execute the function while using the program:

   terminate called after throwing an instance of 'std::invalid_argument'
   what(): stof

Thank you very much, I wonder how to solve it.

  • 1
    Possible duplicate of [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Alan Birtles Apr 03 '19 at 07:38
  • Yes. I realized I just had to move that if some lines up and it works, thanks lol –  Apr 03 '19 at 07:40

0 Answers0