How to disable the escape sequence in C++

帅比萌擦擦* 提交于 2021-02-08 23:13:49

问题


I use C++ to process many files, and I have to write the file name in source code like this: "F:\\somepath\\subpath\\myfile", I wonder that if there's any way to get rid of typing "\\" to get a character '\' in string literal context, i.e, I hope I can just write "F:\somepath\subpath\myfile" instead the boring one.


回答1:


Solutions:

  1. use C++11 string literals: R"(F:\somepath\subpath\myfile)"

  2. Use boost::path with forward slashes: They will validate your path and raise exceptions for problems.

    boost::filesystem::path p = "f:/somepath/subpath";
    p /= "myfile";
    
  3. just use forward slashes; Windows should understand them.




回答2:


If you have C++11, you can use raw string literals:

std::string s = R"F:\somepath\subpath\myfile";

On the other hand, you can just use forward slashes for filesystem paths:

std::string s = "F:/somepath/subpath/myfile";



回答3:


Two obvious options:

  1. Windows understands forward slashes (or rather, it translates them to backslashes); use those instead.
  2. C++11 has raw string literals. Stuff inside them doesn't need to be escaped.

    R"(F:\somepath\subpath\myfile)"
    


来源:https://stackoverflow.com/questions/17164769/how-to-disable-the-escape-sequence-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!