0

Here's the dup: Convert string with explicit escape sequence into relative character


How do I write the fixup() function (below) to make the assertion pass? I would like this to be generalized so that it can handle arbitrary strings which may contain any standard escape sequence.

I'm hoping that there's a simple solution, using standard functions.

/*BINFMTCXX: -Wall -Werror
*/

   #include <string>
   #include <cassert>
   #include <iostream>
   using std::string; using std::cerr;

string fixup( string input ) { return input; }

int main()
   {
   string target="\101";
   string input="\\101";
   string actual=fixup(input);
   cerr<<"target=["<<target<<"], input=["<<input<<"], actual=["<<actual<<"]\n";
   assert( actual == target );
   }

Current output:

target=[A], input=[\101], actual=[\101]
int main(): Assertion `actual == target' failed.

Desired output:

target=[A], input=[\101], actual=[A]
Community
  • 1
  • 1
Brent Bradburn
  • 40,766
  • 12
  • 126
  • 136
  • You do know that "\n" is actually a string that consists of **one** character, not two? If you want proof, print `target.size()`. So how are you possibly going to process a character string that has size 1, thinking that it has a size of 2? The escape sequences are used only for C++ source code, not for interpreting what you may get at runtime. What is the actual problem you're trying to solve? – PaulMcKenzie Mar 02 '17 at 21:26
  • @PaulMcKenzie: Yes, and `\\n` is two characters, which I want to convert to one. – Brent Bradburn Mar 02 '17 at 21:29
  • That doesn't answer the question of `target`, and it doesn't answer the real question -- what problem are you trying to solve? – PaulMcKenzie Mar 02 '17 at 21:31
  • The actual problem is that I want the user to be able to provide `\n` as an input, and my program should treat that as a linefeed. et cetera. – Brent Bradburn Mar 02 '17 at 21:31
  • @PaulMcKenzie: I want a function that converts `input`, which in the example is two characters, to match `target`, which is one character. – Brent Bradburn Mar 02 '17 at 21:32
  • What if the user enters "\\n"? Is that a escape backslash followed by an "n", or is that a single slash followed by a "\n"? – PaulMcKenzie Mar 02 '17 at 21:36
  • It's relatively simple string parsing, until you get to \U####### stuff, then we get into multibyte vs. wide char. Are you willing to forgo \U? – Jfevold Mar 02 '17 at 21:36
  • @PaulMcKenzie: Whatever a C++ compiler does with that is fine for this. – Brent Bradburn Mar 02 '17 at 21:44
  • @Jfevold: I don't know. That probably doesn't matter too much. But I'm trying to avoid doing this manually. I don't want the extra code. – Brent Bradburn Mar 02 '17 at 21:45
  • This was closed as a dup of a question asking for the inverse operation. – Brent Bradburn Mar 02 '17 at 22:07
  • I wonder how many downvotes I've earned just because people don't think my code is purty. – Brent Bradburn Mar 02 '17 at 23:59

0 Answers0