首页 > 解决方案 > 在引号中打印变量 C++

问题描述

给定:

string element = "hello";

我想打印以下内容:

"hello" //with quotation marks

我找到了如何使用“hello”打印带引号的单词,但我想使用我的变量名元素打印出“hello”。

标签: c++

解决方案


你能得到的最接近的

string element = "hello";
std::cout << element

并打印出来

"hello"

是使用std::quoted 这将使代码

string element = "hello";
std::cout << std::quoted(element);

它会输出

"hello"

请注意,std::quoted它的作用远不止添加引号。如果您的字符串包含引号,那么它将修改这些引号并\从中添加一个。这意味着

string element = "hello \"there\" bob";
std::cout << std::quoted(element);

将打印

"hello \"there\" bob"

代替

"hello "there" bob"

推荐阅读