我想将一个 int vector 的值赋给一个 std::string 以便将它传递给另一个函数,现在我写了这段代码:
int input;
std::cout << "Insert the value to convert: \t";
std::cin >> input;
std::string output;
std::vector<int> rem;
int r; //Just a simple binary conversion
while(input != 0) {
r = input % 2;
rem.push_back(r);
input /= 2;
}
std::reverse(rem.begin(), rem.end());
for(std::vector<int>::const_iterator it = rem.begin(); it != rem.end(); ++it) {
output += *it; //Assign every value of the iterator to string variable
}
std::cout << output; Print the value of output
我的代码的问题是字符串包含奇怪的字符,例如 ☺ ☺☺☺ ☺☺☺☺ ☺
...有什么办法可以防止这种情况发生吗?
最佳答案
为什么在添加到输出时不将 int 转换为字符串? 试试这个:
std::stringstream ss;
ss << *it;
std::string str = ss.str();
output += str; //Assign every value of the iterator to string variable
关于C++ - 将 Vector 值分配给 std::string 而不会丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46493669/