c++ - 无法在单独的函数中调用 ifstream

标签 c++ ifstream c++03

我正在学习文件流。我在 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/

相关文章:

c++ - 检查文件是否被进程文件句柄锁定

c++ - Visual Studio 中的 std::transform 使用自己的迭代器失败

c++ - 如何从 C++ 中的二进制文件中删除部分

c++ - 将空 vector 聚合或池化为最大的空 vector ?

c++ - 比较指向不同列表的两个列表迭代器

c++ - 最令人头疼的数组访问解析

c++ - 如何解析cpprestsdk生成的多个Set-Cookie?

c++ - 添加 cout 语句可以更正输出?

c++ - Windows std::ifstream::open() 问题

c++ - 从文件中读取,奇怪的结局