【问题标题】:Can't I use operator ""sv for the parameter of fstream()?我不能将运算符“”sv 用于fstream() 的参数吗?
【发布时间】:2021-06-07 02:55:39
【问题描述】:
#include<iostream>
#include<fstream>

using namespace std::literals;
int main()
{

    auto a = "st"sv;
    std::ifstream in("test.txt"sv, std::ios::in); //error C2664
    std::ifstream in("test.txt"s, std::ios::in);  
}

我正在使用视觉工作室。我不能在 fstream 上使用 string-view literal ""sv 吗?还是我必须设置一些东西?

【问题讨论】:

  • 如果你正在使用 C++17 并进行文件操作,你应该看看std::filesystem::path
  • @Kaldrr 谢谢你,我会检查一下!

标签: c++ c++17 fstream string-view


【解决方案1】:

没有。你不能。

您不能使用它,因为std::ifstream 没有接受std::string_view ref 的ctor 并且std::string_views 和if_stream 接受的类型之间没有隐式转换,因此您必须使用staic_caststd::string 的构造函数进行转换


如果你有一个std::string_view(左值),你可以如下使用它

#include<iostream>
#include<fstream>

using namespace std::literals;
int main()
{

    auto a = "st"sv;
    auto file_location = "test.txt"sv;
    std::ifstream in(std::string(file_location), std::ios::in);  
}

Demo

【讨论】:

  • 在预期 const char * 的地方使用 file_location.data() 是有风险的,不是吗? string_viewdata 不保证为空终止。
  • 谢谢你的回答。但是我还是很好奇为什么 fstream with string 可以,而 string_view 不行。
  • @sunkue 我已经添加了更多解释。
猜你喜欢
  • 2016-12-04
  • 2021-06-30
  • 1970-01-01
  • 2011-08-06
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
  • 2012-06-04
相关资源
最近更新 更多