我正在尝试连接一个具有 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/