//我试图通过在main中调用函数并将文件名作为参数传递来读取函数内部的文件。打开文件时出现错误。但是当我直接传递文件名file(“ file_name”)时,效果也很好。为什么会这样呢?提前致谢。
#include<string>
#include<fstream>
void parse(string file_name)
{
ifstream file("file_name"); //opens file
if (!file)
{
cout<<"Cannot open file\n";
return;
}
cout<<"File is opened\n";
file.close(); //closes file
}
int main()
{
parse("abc.txt"); //calls the parse function
return;
}
删除引号,file_name
并确保用于输入的文件存在于当前工作目录(可执行文件所在的文件夹)中。另外,如果您不使用c++11
,则需要将字符串转换为char*
如下形式:
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
void parse(string file_name)
{
ifstream file(file_name.c_str()); //opens file
if (!file)
{
cout<<"Cannot open file\n";
return;
}
cout<<"File is opened\n";
file.close(); //closes file
}
int main(){
string st = "abc.txt";
parse(st); //calls the parse function
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句