I have a text file and I need to open it via function and then read it via a different function. I can open it but I'm wondering how to read from the file once its opened. Can I just read from it normally?
return InputFile;
}
If I try to use a void function and pass it by reference, it wont compile and I cant figure out where the error is. with this, I can at least get it to run but the cout statement wont work. im getting frustrated!!!!
Go to the links that chervil sent. First you must understand how functions work before we can help otherwise you will just copy/paste.. since you will not understand how it is working.
i understand how functions are supposed to work and I have read the tutorial OVER and OVER but I am not seeing what I am doing wrong. I want a function that gets a file name from the user:
void GetFileName()
{
string DataFileName;
cout << "Enter the name of the file to gather info from (including extension): ";
cin >> DataFileName;
//return (DataFile);
}//end GetFileName
this works fine but I cant pass the DataFileName. I tried adding "string& name"
void GetFileName (string& name) but I get an error.
I would like to pass DataFileName to a function that opens DataFileName.
int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
Notice the function is declared with a type of int, not voidint addition
and then uses the return statement to tell the function which value it is to return.
From the same example, look at the code in main()
1 2
int z;
z = addition (5,3);
Note the variable z is assigned the result when the function is called.
You could use precisely the same mechanism to handle a std::string instead of an int.
The alternative, as you seem to have considered, is to pass a variable by reference, as shown in part 2 of the tutorial.
Not exactly, that's a mixture of different types: int, string and ifstream, almost none of which match the context in which they are used.
Consider this:
1 2 3 4 5 6 7 8 9 10 11 12 13
string getName()
{
string name;
cout << "enter name of file" << endl;
cin >> name;
return name;
}
int main()
{
string NameA;
NameA = getName();
}
Or if you wanted to pass the string by reference, it might look like this:
1 2 3 4 5 6 7 8 9 10 11
void getName(string & name)
{
cout << "enter name of file" << endl;
cin >> name;
}
int main()
{
string NameA;
getName(NameA);
}
I've not used the ifstream at all in these examples, because I wanted to keep things very simple. But as I mentioned in an earlier post, if you want to pass an ifstream parameter to or from a function it will have to be done using the second method (by reference).