【问题标题】:dereferencing string array element c取消引用字符串数组元素 c
【发布时间】:2013-04-07 23:45:05
【问题描述】:

我有一个字符串数组,在一个循环中,我想做这样的事情:

fstream in(fileNames[i], ios::in);

但这不起作用。虽然,当我尝试时:

fstream in("some string",ios::in);

它有效。

我怎样才能完成同样的事情,但使用数组元素?

【问题讨论】:

  • 字符串文件名[NUMTABLES]; fileNames = "这里有一些文字";
  • 你的意思是c还是c++? ios::in 无效 c
  • fstreamios::in?为什么不ifstream

标签: c++ string pointers fstream


【解决方案1】:

在旧的 C++ 中,您必须将 char const * 传递给 fstream 构造函数,所以说:

fstream in(fileNames[i].c_str(), ios::in);
//                     ^^^^^^^^

在 C++11 中,这不再是必需的。

【讨论】:

    【解决方案2】:

    我不确定filenames 的定义是什么,因为它没有在问题中引用。从您的评论string fileNames[NUMTABLES]; filenames = "some text goes here; 看来,string 似乎类似于char。为了创建一个fstream 对象,我们需要传递一个char *,根据上述定义,filenames[i] 被转换为一个简单的char,这可能是问题的原因。

    为了克服这个问题,请找到一个示例代码,其中定义了一个字符串数组,并且fstream 对象已成功创建且没有任何问题。

    char filenames[4][32] = {"Just for testing purposes", "This is for stackoverflow", "Just for enabling", "This is nice program"};
    fstream in(filenames[2], ios::in);
    

    另一种方法是使用strtok 将您的字符串(即some text goes here)分解为更小的字符串,如sometextgoeshere,如下所示

    char *newstr = strtok(filenames, " ");
    fstream in(newstr, ios::in);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-07
      • 2011-01-22
      • 1970-01-01
      • 2012-02-27
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多