您似乎在使用旧版本的C++,其中std::ifstream::open
仅接受const char *
而不是std::string
(请参见文档):
void open (const char* filename, ios_base::openmode mode = ios_base::in);
如您所见,此处无法传递std::string
。
在C++11及更高版本中,您也可以传递std::string
:
void open (const string& filename, ios_base::openmode mode = ios_base::in);
std::string
输入文件名,然后执行 File.open(filename.c_str());
来打开文件。那个建议基本上是错误的。它试图解决的问题是,在旧时代,文件流使用const char*
作为文件名参数,因此您无法直接使用std::string
来命名文件。当然,解决方法是使用std::string
并调用c_str()
来传递文件名:
std::string name = "test.txt";
std::ofstream out(name.c_str());
现在,文件流也有一个接受 std::string
的构造函数,因此您可以这样做:
std::string name = "test.txt";
std::ofstream out(name);
我怀疑这是因为ifstream::open(const char*)
的原型。就个人而言,我会这样编写代码:
string filename;
cin >> filename;
ifstream testmarks;
testmarks.open(filename.c_str());
但这会增加更多的复杂性来解释,显然这是针对C++新手的。
"open"函数需要字符指针。
但是这样做也可以:
std::string filename;
std::cin >> filename;
std::ifsteam f;
f.open(filename.c_str());