Simple question about outputting strings to ofstream.

Started by
1 comment, last by Sneftel 17 years, 1 month ago
Hello all, I have a simple question about outputting strings to the ofstream. In code I have: ofStr<<strMsg; where ofStr is an std::ofstream and strMsg is an std::string Everything works fine except that the formatting character '\' in the string is displayed as a crazy character that I have never seen or used before. I understand that the '\' character is an escape character, but how do I treat it as a non escape character when outputting the string to the ofstream? Thank you for your help. Jeremy (grill8)
Advertisement
It has nothing to do with how you output the string, and everything to do with how you initialize it or otherwise set its contents. The operator<< outputs the exact bytes that are in the string, with no escaping.

The escaping you are thinking of is something that happens at compile time to string literals - i.e., text between double quotes within the actual source code of the program.

If for example you have:

string foo = "foo\bar";cout << foo;


then the \b is interpreted, by the compiler, as a backspace character (ASCII 8, IIRC). The compiler generates code that puts the bytes 'f', 'o', 'o', '\b', 'a', 'r' in order into the string's memory buffer.

To avoid this, escape the backslash itself, by putting two backslashes in a row into the double-quoted string. The system is quite clever, actually: it is designed to make sure that it's possible to create every possible byte-sequence as a string literal (well, except that they all get automatically null-terminated :) ) with relatively little hacking around.

In particular, note that if you wanted a backslash at the end of a string, you would *have* to do this; otherwise, the single backslash followed by double quote would be interpreted as "escape sequence for a double quote within the string literal", and that double-quote would not be interpreted as the end of the literal - this will normally cause compile errors.



BUT. If you are using string literals to specify file paths under DOS/Windows, do not double up backslashes in order to get backslash characters into the file path. Instead, use forward slashes as the path separator. This is guaranteed to work in the C++ standard, and will be automatically portable - i.e., you don't have to change it if you try the code on another OS.
Moved to For Beginners.

This topic is closed to new replies.

Advertisement