我正在学习文件流。我在 main 之外的单独函数中使用 ifstream 时遇到问题。在 main 里面它工作得很好。功能是这样的,
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();
}
函数调用来自 main() 并且是这样的
counter(argv[1]);
我可以只将 ifstream 作为对象传递吗?我不能在 main 之外创建一个吗?
最佳答案
您的问题与函数无关,它与保存文件名的变量有关。考虑:
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
}
通过函数,您将导致从 const char*
到 std::string
的隐式转换,就像上面的示例一样。直到 C++11,std::fstream
才使用 std::string
作为文件名。两种修复方法:
void counter(const char* fname)
{
ifstream inpufile(fname, ios::in); // works now
和 counter(argv[1]);
仍然有效,事实上它工作得更好一点,因为不需要转换。
或者
void counter(std::string fname)
{
ifstream inpufile(str.c_str(), ios::in); // ok too
它获取 fstream
期望的 const char*
。
C++11 最终解决了这个问题,让您可以直接使用 std::string
。
关于c++ - 无法在单独的函数中调用 ifstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26281598/