1

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?

2
  • What does "process all the escape codes" mean? Commented Mar 10, 2020 at 14:58
  • You could use std::string::replace(). Commented Mar 10, 2020 at 15:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I basically added some code to parse the string (Message in the above snippet) and look for escape sequences, and replace the text with the escape sequence... So look for the \n and replace it with "\n" in a new string. And that's working. It's just a pain to do this for each sequence...But at least it works. Thanks again for the confirmation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.