1

I am quiet new with C++ and I need to read an input from a MSVC++ text-field and write it to a file. I need to write \n as a new line to the file and not as \n.

After some researching I found that escape characters only work at compile-time. Is it possible for me to use it on run-time. I am only using C++ for this task.

1
  • 1
    Just look for that sequence of char when loading the text, and replace it with a newline char. Commented Nov 10, 2014 at 5:29

1 Answer 1

3

I might write this a bit differently if I were doing it in C++ today (I wrote this in C around 20 years ago), but it might at least provide a little inspiration:

/*
** Public Domain by Jerry Coffin.
**
** Interprets a string in a manner similar to that the compiler
** does string literals in a program.  All escape sequences are
** longer than their translated equivalant, so the string is
** translated in place and either remains the same length or
** becomes shorter.
*/

#include <string.h>
#include <stdio.h>
#include "snip_str.h"

char *translate(char *string)
{
      char *here=string;
      size_t len=strlen(string);
      int num;
      int numlen;

      while (NULL!=(here=strchr(here,'\\')))
      {
            numlen=1;
            switch (here[1])
            {
            case '\\':
                  break;

            case 'r':
                  *here = '\r';
                  break;

            case 'n':
                  *here = '\n';
                  break;

            case 't':
                  *here = '\t';
                  break;

            case 'v':
                  *here = '\v';
                  break;

            case 'a':
                  *here = '\a';
                  break;

            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
                  numlen = sscanf(here,"%o",&num);
                  *here = (char)num;
                  break;

            case 'x':
                  numlen = sscanf(here,"%x",&num);
                  *here = (char) num;
                  break;
            }
            num = here - string + numlen;
            here++;
            memmove(here,here+numlen,len-num );
      }
      return string;
}
Sign up to request clarification or add additional context in comments.

Comments

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.