Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quoting strings in C++

In Pascal Lazarus/Delphi, we have a function QuotedStr() that wraps any string within single quotes.

Here's an example of my current C++ code:

//I need to quote tblCustomers
pqxx::result r = txn.exec( "Select * from \"tblCustomers\" "); 

Another one:

//I need to quote cCustomerName
std::cout << "Name: " << r[a]["\"cCustomerName\""];

Similar to the above, I have to frequently double-quote strings. Typing this in is kind of slowing me down. Is there a standard function I can use for this?

BTW, I develop using Ubuntu/Windows with Code::Blocks. The technique used must be compatible across both platforms. If there's no function, this means that I must write one.

like image 821
itsols Avatar asked Mar 27 '26 18:03

itsols


2 Answers

C++14 added std::quoted which does exactly that, and more actually: it takes care of escaping quotes and backslashes in output streams, and of unescaping them in input streams. It is efficient, in that it does not create a new string, it's really a IO manipulator. (So you don't get a string, as you'd like.)

#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
  std::string in = "\\Hello \"Wörld\"\\\n";

  std::stringstream ss;
  ss << std::quoted(in);
  std::string out;
  ss >> std::quoted(out);
  std::cout << '{' << in << "}\n"
            << '{' << ss.str() << "}\n"
            << '{' << out << "}\n";
}

gives

{\Hello "Wörld"\
}
{"\\Hello \"Wörld\"\\
"}
{\Hello "Wörld"\
}

As described in its proposal, it was really designed for round-tripping of strings.

like image 84
akim Avatar answered Mar 31 '26 09:03

akim


Using C++11 you can create user defined literals like this:

#include <iostream>
#include <string>
#include <cstddef>

// Define user defined literal "_quoted" operator.
std::string operator"" _quoted(const char* text, std::size_t len) {
    return "\"" + std::string(text, len) + "\"";
}

int main() {
    std::cout << "tblCustomers"_quoted << std::endl;
    std::cout << "cCustomerName"_quoted << std::endl;
}

Output:

"tblCustomers"
"cCustomerName"

You can even define the operator with a shorter name if you want, e.g.:

std::string operator"" _q(const char* text, std::size_t len) { /* ... */ }
// ...
std::cout << "tblCustomers"_q << std::endl;

More info on user-defined literals

like image 34
Felix Glas Avatar answered Mar 31 '26 09:03

Felix Glas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!