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

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

c++ - Convert string with explicit escape sequence into relative character

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

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

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...