用C++引用字符串

its*_*ols 1 c++ string double-quotes

在Pascal Lazarus/Delphi中,我们有一个函数QuotedStr(),它将任何字符串包装在单引号中.

这是我当前的C++代码示例:

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

另一个:

//I need to quote cCustomerName
std::cout << "Name: " << r[a]["\"cCustomerName\""];
Run Code Online (Sandbox Code Playgroud)

与上面类似,我必须经常双引号.输入这个有点让我失望.我可以使用标准功能吗?

顺便说一下,我使用带有Code :: Blocks的Ubuntu/Windows开发.所使用的技术必须兼容两个平台.如果没有功能,这意味着我必须写一个.

Snp*_*nps 6

使用C++ 11,您可以创建用户定义的文字,如下所示:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

"tblCustomers"
"cCustomerName"
Run Code Online (Sandbox Code Playgroud)

如果需要,您甚至可以使用较短的名称定义运算符,例如:

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

有关用户定义的文字的更多信息

  • @doctorlove`17.6.4.3.5 - 不以下划线开头的文字自定义标识符保留用于将来的标准化. (6认同)

aki*_*kim 5

C ++ 14增加了std::quoted它的功能,实际上更确切地说:它负责在输出流中转义引号和反斜杠,并在输入流中转义它们。它很有效,因为它不会创建新的字符串,它实际上是IO操作器。(因此,您不会得到想要的字符串。)

#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";
}
Run Code Online (Sandbox Code Playgroud)

给

{\Hello "Wörld"\
}
{"\\Hello \"Wörld\"\\
"}
{\Hello "Wörld"\
}
Run Code Online (Sandbox Code Playgroud)

正如在描述其提案,当时真是专为字符串的往返。