使用字符串或字符数组作为文件名?

4

我在网上看到了一些关于字符串的内容。它说要使用char数组作为文件名输入,而不是字符串。为什么?

Slide


在线教程中有很多错误的建议,这只是其中之一。 - drescherjm
5个回答

3

您似乎在使用旧版本的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()); 来打开文件。

2

那个建议基本上是错误的。它试图解决的问题是,在旧时代,文件流使用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);

2

我怀疑这是因为ifstream::open(const char*)的原型。就个人而言,我会这样编写代码:

    string filename;
    cin >> filename;
    ifstream testmarks;
    testmarks.open(filename.c_str());

但这会增加更多的复杂性来解释,显然这是针对C++新手的。


1
这是错误的,而且这种写法容易导致缓冲区溢出,至少在示例中是这样的。

0

"open"函数需要字符指针。

但是这样做也可以:

std::string filename;
std::cin >> filename;

std::ifsteam f;
f.open(filename.c_str());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接