I am learning filestreams. I have a problem while using ifstream in a separate function outside main. Inside main it works just fine. the function is such,
void counter(string str)
{
ifstream inpufile(str,ios::in);//the error is here, it says the function cannot be called!?!
if(!inpufile)
{
cout<<"\n The file does not exist, try again";
}
else
{
char c;
int counter=0;
while(inpufile.get(c))
{
if(c=='\n')
counter++;
}
cout<<"\n The number of lines in the file are "<<counter+1;
}
inpufile.close();
}
The function call is from main() and is such
counter(argv[1]);
Can I only pass ifstream as an object. Can I not create one outside main?
Your problem doesn't have anything to do with the function, it has to do with the variable holding the filename. Consider:
int main(int argc, const char** argv)
{
std::ifstream inpufile(argv[1], ios::in); // ok
std::string fname = argv[1]; // ok
std::ifstream fileb(str, ios::in); // fails pre-C++11
}
By having a function, you're causing an implicit conversion from const char*
to std::string
, just like in the example above. And std::fstream
didn't take std::string
for the filename until C++11. Two ways to fix:
void counter(const char* fname)
{
ifstream inpufile(fname, ios::in); // works now
and counter(argv[1]);
still works, in fact it works a tiny bit better because no conversion is needed.
Or
void counter(std::string fname)
{
ifstream inpufile(str.c_str(), ios::in); // ok too
Which gets the const char*
that fstream
expects.
C++11 does finally fix this and let you use std::string
directly.