c++ - 将 vector 大小连接到字符串

标签 c++ string vector

我正在尝试连接一个具有 vector 大小的字符串。无论我使用什么方法,我都没有得到想要的输出。当我使用 cout 时,它打印良好,当我在调试器中查看字符串的值时,它显示为 Schemes(\002)。问题是:我需要返回一个字符串,而不是直接打印到控制台,所以我不能使用 cout;我必须使用串联。为什么字符串和 vector 大小没有按预期连接?

需要的字符串: schemes(2)

输出的字符串: schemes()

代码:

using namespace std;    

string s;
vector<Object> schemes;

// Add two elements to vector

// Method 1 (doesn't work)
s += "Schemes(" + schemes.size();
s += ")"; // I can't put this on the same line because I get 'expression must have integral or unscoped enum type' error

// Method 2 (doesn't work)
s += "Schemes(";
s.push_back(schemes.size());
s += ")";

// Method 3 (doesn't work)
s += "Schemes(";
s.append(schemes.size());
s += ")";

最佳答案

schemes.size() 是整数类型。这意味着您正在尝试将整数类型连接到字符串类型。

尝试

s = "Schemes(" + to_string(schemes.size()) + ")";

关于c++ - 将 vector 大小连接到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54432638/

相关文章:

c++ - 空 vector 是其结构的大小吗?

c++ - 按照符号链接(symbolic link)并使用 QFileInfo 获取绝对路径

java - 转换日期中的字符串值时出现小问题

javascript - 减法运算符如何触发数组到数字的转换?

java - 如何防止 substr() 上出现 NullPointerException?

C++ vector::erase 问题与 OpenCV 代码

c++ - 当你完美转发时,typename T 变成 T& 或 T&&,但当你不这样做时,T 根本不是引用。如何?

c++ - 运算符 *= 在 C++ 中重载

c++ - 混淆三种引用形式

c++ - 使用子字符串 C++ 获取奇怪的输出