Vcsn  2.1
Be Rational
escape.cc
Go to the documentation of this file.
1 #include <vcsn/misc/escape.hh>
2 
3 #include <cctype>
4 #include <iomanip>
5 #include <iostream>
6 #include <sstream>
7 
8 namespace vcsn
9 {
10  // Accept int to catch EOF too.
11  std::ostream&
12  str_escape(std::ostream& os, const int c)
13  {
14  std::ios_base::fmtflags flags = os.flags(std::ios_base::hex);
15  char fill = os.fill('0');
16  switch (c)
17  {
18  case -1: os << "<end-of-file>"; break;
19  case '\\': os << "\\\\"; break;
20  case '"': os << "\\\""; break;
21  case '\n': os << "\\n"; break;
22  default:
23  if (0 <= c && c <= 0177 && std::isprint(c))
24  os << char(c);
25  else
26  os << "\\x" << std::setw(2) << c;
27  break;
28  }
29  os.fill(fill);
30  os.flags(flags);
31  return os;
32  }
33 
34  std::string
35  str_escape(const int c)
36  {
37  std::ostringstream o;
38  str_escape(o, c);
39  return o.str();
40  }
41 
42  std::ostream&
43  str_escape(std::ostream& os, const std::string& str)
44  {
45  for (auto c: str)
46  // Turn into an unsigned, otherwise if c has its highest but
47  // set, will be interpreted as a negative char, which will be
48  // mapped to a negtive int. So for instance c = 255 is mapped
49  // to \xFFFFFFF instead of 255.
50  //
51  // This happens only when char is "signed char". Which is
52  // common.
53  str_escape(os, uint8_t(c));
54  return os;
55  }
56 
57  std::string
58  str_escape(const std::string& s)
59  {
60  std::ostringstream o;
61  str_escape(o, s);
62  return o.str();
63  }
64 }
std::ostream & str_escape(std::ostream &os, const std::string &str)
Output a string, escaping special characters.
Definition: escape.cc:43
std::ostringstream os
The output stream: the corresponding C++ snippet to compile.
Definition: translate.cc:374