Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need a function to convert "explicit" escape sequences into the relative non-printable character. Es:

char str[] = "\n";
cout << "Line1" << convert_esc(str) << "Line2" << endl:

would give this output:

Line1

Line2

Is there any function that does this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
493 views
Welcome To Ask or Share your Answers For Others

1 Answer

I think that you must write such function yourself since escape characters is a compile-time feature, i.e. when you write " " the compiler would replace the sequence with the eol character. The resulting string is of length 1 (excluding the terminating zero character).

In your case a string "\n" is of length 2 (again excluding terminating zero) and contains and n.

You need to scan your string and when encountering check the following char. if it is one of the legal escapes, you should replace both of them with the corresponding character, otherwise skip or leave them both as is.

( http://ideone.com/BvcDE ):

string unescape(const string& s)
{
  string res;
  string::const_iterator it = s.begin();
  while (it != s.end())
  {
    char c = *it++;
    if (c == '\' && it != s.end())
    {
      switch (*it++) {
      case '\': c = '\'; break;
      case 'n': c = '
'; break;
      case 't': c = ''; break;
      // all other escapes
      default: 
        // invalid escape sequence - skip it. alternatively you can copy it as is, throw an exception...
        continue;
      }
    }
    res += c;
  }

  return res;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...