-
Reading from a file
Hi
I am trying to read a file and then print out information about that file using a function.
Here is the code i have so far:
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream in;
void NoOfChars();
int main()
{
string file;
cout << "Enter the file name you wish to open: " << endl;
cin >> file;
cout << "The file you wish to open is: " << file <<endl;
in.open(file);
if (in.fail())
{
cout << "File failed to open" << endl;
}
// Then print out the information here
cout<<"Number of Chars: "<< NoOfChars(in)<<endl;
}
void NoOfChars()
{
//Function code here
return chars;
}
My question is, do i have the right idea?
Thanks
-
That's a start. A couple notes though:
- You can't pass parameters to a function that doesn't take any.
- You can't return a value from a function that returns void.
- If you fail to open the file, you should exit the application instead of just printing a message.
- Avoid global variables where possible. In this case, "in" should be declared in the main function.
-
Since file is a std::string you must convert the std::string to a C-string for this call to open:
Code:
in.open(file.c_str());
Code:
void NoOfChars()
{
//Function code here
return chars;
}
Since you have defined your function to return nothing (void) you can not return anything. Also your function prototype, function definition, and function call must all agree on the number and type of parameters, and the return type. You have defined this function to take no arguments but in your function call you are trying to pass a parameter.
Jim
-
Cheers for the replys. The function should have the prototype int NoOfChars()
-
I have solved the problem. Thanks