【发布时间】:2016-08-17 21:05:55
【问题描述】:
【问题讨论】:
-
在线教程中有很多不好的建议。这只是其中之一..
【问题讨论】:
您似乎使用的是旧版本的 C++,其中 std::ifstream::open 只接受 const char *,而不接受 std::string(请参阅 docs):
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 输入文件名并使用do 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++ 不熟悉的人。
【讨论】:
这是错误的,这是编写易受缓冲区溢出影响的程序的绝妙方法,至少在示例中如此编写。
【讨论】:
“打开”函数需要字符指针。
但是这样做很好:
std::string filename;
std::cin >> filename;
std::ifsteam f;
f.open(filename.c_str());
【讨论】: