C++ 尝试打开和关闭函数中的文件

C++ 尝试打开和关闭函数中的文件,c++,function,ifstream,C++,Function,Ifstream,无法运行我的num_of_line函数。我确实需要打开和关闭函数中的文件,并且还必须对其他几个函数执行同样的操作。这是为了让我可以从文件的请求中获得信息(我不能使用任何其他允许我这样做的函数,因为我们还没有在课堂上学习它们)。我有两个错误: hello.cpp:14:17: error: use of undeclared identifier 'file'; did you mean 'fill'? ilines.open(file); //does file

无法运行我的num_of_line函数。我确实需要打开和关闭函数中的文件,并且还必须对其他几个函数执行同样的操作。这是为了让我可以从文件的请求中获得信息(我不能使用任何其他允许我这样做的函数,因为我们还没有在课堂上学习它们)。我有两个错误:

hello.cpp:14:17: error: use of undeclared identifier 'file'; did you mean
      'fill'?
    ilines.open(file);        //does file need to be a c-string
                ^~~~
                fill

hello.cpp:14:12: error: no matching member function for call to 'open'
    ilines.open(file);        //does file need to be a c-string
不知道该怎么办,谢谢

#include <iostream>
#include <fstream>
#include <cctype>
#define die(errmsg) {cerr << errmsg << endl; exit(1);} 
using namespace std;

int num_of_lines(string name)
{
    int cnt3 = 0;
    string line;

    ifstream ilines;     //Do I need to check for successful opening and closing each time

    ilines.open(file);        //does file need to be a c-string

    if(ilines.is_open())
    {
        while(getline(ilines, line))cnt3++;   
    }  
    ilines.close(); 
    return(cnt3);
}


int main(int argc, char **argv)
{ 
    int num_of_lines(string name);

    string file;
    file = argv[1];

    if(argc == 1)die("usage: mywc your_file"); 

    ifstream ifs;

    ifs.open(file);

    if(ifs.is_open())
    {

        ifs.close();

        int a;

        a = num_of_lines(file);
        cout <<"Lines: " << a << endl;
    }
    else
    {
        cerr <<"Could not open: " << file << endl;
        exit(1);
    }

    //ifs.close();

    return(0);
}
#包括
#包括
#包括

#定义die(errmsg){cerr您有两个问题

  • 变量
    file
    未在
    num\u of_line
    中定义。使用
    file
    作为参数而不是'name',可以非常轻松地修复该变量

    int num_of_lines(string file)
    {
       ...
    }
    
    你也可以使用

    int num_of_lines(string const& file)
    {
       ...
    }
    
    避免复制
    std::string

  • <> L> >代码>文件< /C> >类型<代码> STD::String ,您可能不得不使用“代码>文件.cxStrand()/Cudio),这取决于您的编译器支持的C++标准版本。 如果您有兼容C++11的编译器,则可以使用:

    string file;
    ifstream ilines;
    ilines.open(file);
    
    如果您只有符合C++03的编译器,则必须使用:

    string file;
    ifstream ilines;
    ilines.open(file.c_str());
    

    您的参数名为
    name
    …是的,它必须是一个C样式的字符串,您可以这样得到:
    name.C_str()
    I将ifs.open(file)更改为ifs.open(name.C_str()),并且我得到分段错误:11
    file=argv[1];if(argc==1)死亡(“用法:mywc-Your_file”)
    的方法是错误的:您需要先检查
    argc
    ,然后访问
    argv[1]
    。这是否为您编译?您对(int i=2;i是什么意思
    ?字符**
    大小是多少?为什么缺少迭代
    ++i
    ?除了多次尝试关闭
    ifs
    而不再次打开它之外,您的循环做了什么?您不应该在这个循环中不断更新
    名称/文件
    ?编译后调用它时,您是否给它一个文件名这对我来说似乎不管用,至少它不会因为一个空的输入文件而消亡……还有一些其他问题