【问题标题】:C++ parameters of an input stream输入流的 C++ 参数
【发布时间】:2011-12-28 08:30:16
【问题描述】:

我只是想知道,是否可以让用户在尝试使用流时输入文件的位置?

例如我想做什么:

int main()
{
ifstream instream; 

string file_location;
cout << "Enter in file location: " << endl; 
cin >> file_location;
instream.open(file_location);
}

所以我希望他们输入文件位置,但程序不会编译。

我得到的错误信息是:

没有匹配函数调用'std::basic_ifstream >::open(std::string&)'

【问题讨论】:

    标签: parameters input stream


    【解决方案1】:

    你的想法是对的,但你的类型有点不正确。 open 采用 const char*,而不是 std::string,因此您需要提供字符串包含的 const char*。 std::string 的c_str() method 将返回代表 std::string 的 const char*。

    例如:

    instream.open(file_location.c_str());
    

    【讨论】:

    • 转成cstring后还是报错:request for member 'c_str' in 'file_location', which is non-class type 'char'
    • @kol:原来如此,你的帖子在我还在打字的时候就发布了,所以我给你投票了。
    • @knguyen2525:有些事情并没有完全加起来......你在做一个你没有提到的数组索引吗?请参阅此 SO 帖子:stackoverflow.com/questions/1694798/…
    • 我让它工作了。我应该将其保留为类型字符串并将其转换为 cstring。感谢大家的帮助!
    【解决方案2】:

    请改用instream.open(file_location.c_str());

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      相关资源
      最近更新 更多