首页 > 解决方案 > 将向量大小连接到字符串

问题描述

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

所需字符串:方案(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 += ")";

标签: c++stringvector

解决方案


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

尝试

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

推荐阅读