Collect an integer from a file

0

The program consists of writing a number (in this case 1) in a file and then opening the file and displaying it on the screen. The problem is that I do not know how to pick up an int.

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
    int c;

    ofstream ficheroSalida;
    ficheroSalida.open("almacen.txt");
    ficheroSalida << 1 ;
    ficheroSalida.close();

    fstream ficheroEntrada;
    ficheroEntrada.open("almacen.txt");
    if(ficheroEntrada.is_open())
    {
        while(!ficheroEntrada.eof())
        {
            ficheroEntrada.get(c);
        }
        cout << c;
    }
    return 0;
}
    
asked by Vendetta 16.12.2017 в 19:57
source

1 answer

2

First you must capture what comes from the file as a string, then you have to convert that string to integer with the function atoi (string); Bookseller Inventory # cstdlib.

int c;
string r;

ofstream ficheroSalida;
ficheroSalida.open("almacen.txt");
ficheroSalida << 1 ;
ficheroSalida.close();

fstream ficheroEntrada;
ficheroEntrada.open("almacen.txt", ios_base::in);
if(ficheroEntrada.is_open())
{
    while(!ficheroEntrada.eof())
        getline(ficheroEntrada, r);
    c = atoi(r.c_str());
    cout << c;
}
return 0;

Do not forget to add the cstdlib library

    
answered by 16.12.2017 / 20:15
source