Andy D
Andy D

Reputation: 38

Formatting output from strings in C++

To be honest - not sure how to phrase the question title. But basically I want to have a C++ program which allows input of a string (message) and a color - and it will output the string in that color to the console. Like PowerShell does with "Write-Host" and "-ForegroundColor".

And I have it all working just fine. Except that I want the ability to automatically process escape sequences. So if I run this:

c:\>myprogram.exe -Message "Hello there" -ForegroundColor Green

I get "Hello there" in green. Great so far. But if I do this:

c:\>myprogram.exe -Message "Hello\nthere" -ForegroundColor Green

I get "Hello\nthere" on one line. Because of the \n I would like to see this on 2 lines. Same with a \t - I would like that interpreted and to see a tab in the output.

After all the color processing, this is basically what the code is doing:

//
// Display the message
//

Message += "\n";
std::cout << Message;
printf("%s", Message.c_str());

Both printf and std::cout are there currently just to see if either behaves differently - they don't. I guess that the line Message += "\n"; gets processed internally to add an actual new line rather than processed when sent to std::cout or printf because that final new line does get processed as expected. But when contained in the variable Message as provided in an input argument... it doesn't.

Is there a way to just process all the escape codes in a string? Or would I have to basically manipulate the string, i.e., break it up based on the \n and output each section of the string individually?

Upvotes: 1

Views: 88

Answers (1)

josh poley
josh poley

Reputation: 7479

C / C++ string escape sequences are interpreted by the compiler, not the run-time system. So yes, you would have to perform your own run-time string parsing to handle the custom escape sequences you want to support.

Upvotes: 1

Related Questions