使用变量名打开文件
Opening a file using a variable name
如果我将myfile("input.txt")更改为myfile(file_name)…其中file_name传递给函数,它不起作用,但给出错误没有匹配的函数调用…我猜b.c.我不应该传递字符串给构造函数…如果不是这样,怎么做?
void file_to_string(string file_name)
{
string line;
ifstream myfile("input.txt");
if(myfile.is_open())
{
while(myfile.good())
{
getline(myfile,line);
cout << line;
}
myfile.close();
}
else
{
cout << "File : " << file_name << " : did not open" ;
}
}
int main(int argc, char *argv[])
{
file_to_string(argv[1]);
}
使用std::string
类中的c_str()
成员:
ifstream myfile(file_name.c_str());
它返回一个以空结束的const char *
表示的字符串,这正是你在这里需要的。
file_name
是std::string
,但ifstream
构造函数想要一个普通的c风格字符串(指向char
的指针)。所以使用:
iftsream myfile(file_name.c_str());
这是库中一个相当不干净的部分,恕我冒犯,因为流库比STL更老(std::string
是从STL中提取的)。所以流库并不真正了解std::string
。这也是为什么std::getline(std::istream&, std::string&)
是一个独立的功能(和<string>
的一部分,而不是<istream>
或类似的东西),我想。
可以看作是组件的干净分离,但我认为std::string
应该是c++中字符串的标准,因此也可以被流库使用(至少它的接口)。由于标准库总是被视为一个整体,因此这只是组件干净地协同工作的一个糟糕示例。也许未来的标准会解决这个问题。
EDIT:根据Benjamin的评论(以及我对标准草案的阅读)c++ 11似乎确实解决了这个问题,你现在可以使用std::string
作为文件名。但是我猜你还没有用c++ 11
std::ifstream的构造函数接受文件名为const char*。可以使用c_str()成员函数将std::string类型转换为const char*类型。
void file_to_string(string file_name)
{
string line;
ifstream myfile(file_name.c_str()); //convert string to const char*
if(myfile.is_open())
{
while(myfile.good())
{
getline(myfile,line);
cout << line;
}
myfile.close();
}
else
{
cout << "File : " << file_name << " : did not open" ;
}
}
int main(int argc, char *argv[])
{
file_to_string(argv[1]);
}
ifstream接受const char*作为参数,因此不能传递std::string给它。也许你可以试试:
std::string fileName;
... // fill fileName
ifstream myfile( fileName.c_str() );
- 你能重载对象变量名本身返回的内容吗
- 在C/C++中将变量名定义为__00000001有什么好处吗
- C++变量名(可以将 main 声明为变量,但对于其他函数名称则不然)
- 如何按文件扩展名引用文件夹中的文件
- C++ - 声明中变量名后面的括号
- 谁能告诉我,程序中的错误是什么?该程序仅用于获取文件扩展名
- 如何使替换 c 函数的变量名成为错误?
- 通过cMake使用具有自定义文件扩展名的共享库
- 在另一个字符串中插入文件扩展名之前的字符串
- 是否可以创建没有变量名的变量
- fstream库,试图创建一个变量名为(c++)的文件
- 一个数组C++中的消息和变量名
- 在变量名后声明带有 () 的非内部类型与不使用变量名的行为不同。即 std::map<int,char>x(); - 这是怎么回事?
- 如何在不使用文件扩展名的情况下使用命令行参数打开C++中的文本文件?
- 数组的变量名和该数组的地址有什么区别?
- Eclipse CDT:传递具有相同文件扩展名的多个程序参数
- 如何在从.txt文件中读取时不重复相同的变量名
- 如何从保存在.c,.cpp文件中的c,c++代码中提取变量名
- 用c++解析PDB文件收集变量名
- 使用变量名打开文件