How to pass variable normally by value by reference?

1

I want to pass the variable tabe (which is of type ifstream ) by reference to a function (I do not want a copy of it, just that the function to change it), well, I do not quite understand how it is done that.

Code:

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


string apaga_espaco(ifstream* tabe)
{

string s;
char N;
while ((tabe*).good())
{
    getline((tabe*), s);
    s.erase(0,29);
    N=s.find(':');
    s.erase(0,N+6);
    return 0;
}

}

 int main()
{
    ifstream tabe;
    char N;

    tabe.open("Tabela.txt", ios::in);

    if (!tabe.is_open())
    {
        cout << "Arquivo nao encontrado, erro fatal!";
        exit(1);
    }

    apaga_espaco(*tabe);

}
    
asked by anonymous 29.09.2015 / 01:34

2 answers

2

I will not look at all your code to see if there are more errors. If given to understand what you want to do is pass by reference. So just declare the type of the parameter as a reference. The rest works in a natural way. No need to use pointers.

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

void apaga_espaco(ifstream& tabe) {
    string s;
    char N;
    while (tabe.good()) {
        getline(tabe, s);
        s.erase(0, 29);
        N = s.find(':');
        s.erase(0, N + 6);
    }
}

int main() {
    ifstream tabe;
    char N;

    tabe.open("Tabela.txt", ios::in);
    if (!tabe.is_open()) {
        cout << "Arquivo nao encontrado, erro fatal!";
        exit(1);
    }
    apaga_espaco(tabe);
}

See almost running on ideone (it does not have the file).

    
29.09.2015 / 01:51
1

Most people who program in c ++ have passed C before, but c ++ has some quirks, and one of them is passing by reference. in the code in C to be able to change the value of the original variable we have to pass the pointer as parameter in the function, but in C ++ it is enough that we pass the address of this variable that it will be changed, and within our function we can work with the variable as if we were only working with a copy, but in fact we are changing the original variable. so instead of signing the function to be

string apaga_espaco(ifstream * tabe)

Just so be it

void apaga_espaco(ifstream & tabe)

where & means that you are passing the tab memory address. one thing that left me confused was you declare a function that returns a string and returns 0 at the end. :

    
30.09.2015 / 03:25