Reputation:
My latest homework assignment is to write a program that reads a textfile and outputs the number of lines, words and characters.
I'm just starting out, all I'm trying to do right now is to let the user type in the file name and then the file will open. This is my not-working code, I must be missing something obvious, I'm just trying to pass the stream and char to the 'input' function.
Any pointers?
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
//Define functions.
void input(ifstream& fin, char& fileName);
int main()
{
ifstream fin;
char fileName[20];
input(fin, fileName);
return 0;
}
void input(ifstream& fin, char& fileName)
{
cout << "Input file name: ";
cin >> fileName;
fin.open(fileName);
if(fin.fail())
{
cout << "The file: " << fileName << " does not open." << endl;
exit(1);
}
//return;
}
Upvotes: 0
Views: 241
Reputation: 4988
your input
function's second param: char& fileName
is a reference to a char; whereas - what you need is a reference to an array of 20 chars
Thus, change it to: void input(ifstream& fin,
char (&fileName)[20])
Upvotes: 0
Reputation: 1
Your syntax isn't correct. Use:
void input(ifstream *fin, char *fileName);
And:
input(&fin, &fileName); // call
Here you are passing the reference of the variable to the pointer (*
).
Make the required changes and it should work fine.
Upvotes: 0
Reputation: 92271
One problem is that char&
is a reference to a single char
, not an array or a string.
This will work much better if you use std::string fileName
, and pass a string&
parameter around.
Upvotes: 0
Reputation: 66224
This will probably get you closer. At least past your compilation errors, but you still need work on a few things. Get thee to a reference manual and a debugger.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
//Define functions.
void input(ifstream& fin, string& fileName);
int main()
{
ifstream fin;
string fileName;
input(fin, fileName);
return 0;
}
void input(ifstream& fin, string& fileName)
{
cout << "Input file name: ";
cin >> fileName;
fin.open(fileName.c_str());
if(fin.fail())
{
cout << "The file: " << fileName << " does not open." << endl;
exit(1);
}
//return;
}
Not the way I'd do this, but you gotta learn sometime. Good luck!
Upvotes: 1