Raw and Cooked String Processing in C++

By John Paul Mueller, Jeff Cogswell

There are many ways to define literals. Of course, the kind of information that a literal affects is the most common method. However, literals can also be raw or cooked. A raw literal receives input from the application source and doesn’t interpret it in any way. What this means is that the information is interpreted character by character, precisely as the sender has presented it.

Cooked literals interpret the sender’s input and automatically perform any required conversions to make the data usable to the recipient.

The easiest way to see this principle in action is through an example. The RawAndCooked example shown demonstrates the technique used to create either raw or cooked string processing.

#include <iostream>
using namespace std;
int main()
{
    auto Cooked = "(HellornThere)";
    auto Raw = R"(HellornThere)";
    cout << Cooked << endl;
    cout << Raw << endl;
}

Most of the time when you see the rn combination, you know that the application will output a carriage return and line feed combination. This is the cooked method of processing a string.

The string is interpreted and any escape characters converted into control characters (characters that are normally regarded as commands, rather than data, such as the carriage return). However, notice how the Raw string is created. The R in front of the string tells the compiler to create the variable without interpreting the content.

Here’s the output you see from this example:

 (Hello
There)
HellornThere

Notice that the cooked form does output the parenthesis, but the raw form doesn’t. The parenthesis is required as part of the raw form input. As you might imagine, the cooked form outputs the rn combination as control characters, while the raw form outputs the actual characters.