Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable the escape sequence in C++

Tags:

c++

path

escaping

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.

like image 604
Zhiwei Chen Avatar asked Jun 18 '13 09:06

Zhiwei Chen


People also ask

How do you ignore escape sequence?

To ignoring escape sequences in the string, we make the string as "raw string" by placing "r" before the string. "raw string" prints as it assigned to the string.

What is use of '\ r escape sequence in C?

\r (Carriage Return) – We use it to position the cursor to the beginning of the current line. \\ (Backslash) – We use it to display the backslash character. \' (Apostrophe or single quotation mark) – We use it to display the single-quotation mark.

Which is not a escape sequence character in C?

The line continuation sequence (\ followed by a new-line character) is not an escape sequence. It is used in character strings to indicate that the current line of source code continues on the next line. The value of an escape sequence represents the member of the character set used at run time.


3 Answers

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.

like image 64
utnapistim Avatar answered Oct 19 '22 02:10

utnapistim


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)"
    
like image 20
cHao Avatar answered Oct 19 '22 01:10

cHao


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";
like image 28
juanchopanza Avatar answered Oct 19 '22 02:10

juanchopanza