【问题标题】:Use string or array of char for filename?使用字符串或字符数组作为文件名?
【发布时间】:2016-08-17 21:05:55
【问题描述】:

我在网上看到了一些关于字符串的东西。它说使用chars 的数组作为文件名输入而不是字符串。这是为什么呢?

【问题讨论】:

  • 在线教程中有很多不好的建议。这只是其中之一..

标签: c++ arrays string char


【解决方案1】:

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

【讨论】:

    【解决方案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);
    

    【讨论】:

      【解决方案3】:

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

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

      但要解释这一点更多复杂,这显然是针对那些非常对 C++ 不熟悉的人。

      【讨论】:

        【解决方案4】:

        这是错误的,这是编写易受缓冲区溢出影响的程序的绝妙方法,至少在示例中如此编写。

        【讨论】:

          【解决方案5】:

          “打开”函数需要字符指针。

          但是这样做很好:

          std::string filename;
          std::cin >> filename;
          
          std::ifsteam f;
          f.open(filename.c_str());
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-01-12
            • 2022-06-28
            • 1970-01-01
            • 2020-03-02
            • 1970-01-01
            • 2011-07-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多