C++ 尝试打开和关闭函数中的文件
无法运行我的num_of_line函数。我确实需要打开和关闭函数中的文件,并且还必须对其他几个函数执行同样的操作。这是为了让我可以从文件的请求中获得信息(我不能使用任何其他允许我这样做的函数,因为我们还没有在课堂上学习它们)。我有两个错误: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
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()),并且我得到分段错误:11file=argv[1];if(argc==1)死亡(“用法:mywc-Your_file”)
的方法是错误的:您需要先检查argc
,然后访问argv[1]
。这是否为您编译?您对(int i=2;i是什么意思
?字符**的大小是多少?为什么缺少迭代++i
?除了多次尝试关闭ifs
而不再次打开它之外,您的循环做了什么?您不应该在这个循环中不断更新名称/文件
?编译后调用它时,您是否给它一个文件名这对我来说似乎不管用,至少它不会因为一个空的输入文件而消亡……还有一些其他问题