C++中将vector<int>转为字符串输出为[,,,,]的错误原因求解
问题原因
你的代码核心问题是直接将int类型的数值传入std::string的push_back方法导致的:
push_back方法仅接受char类型参数,直接传入elements.at(i)返回的int值时,程序会将数字当作ASCII码值处理:比如你传入数字6,对应ASCII码里的不可见控制字符,自然不会显示为肉眼可见的数字字符'6',所以最终输出里只有你主动添加的逗号和方括号能正常显示。- 如果vector元素都是个位数,也可以用
elements.at(i) + '0'的方式把int转为对应的数字字符再调用push_back;如果存在多位数元素,必须先把int类型的元素转换为对应的数字字符串,再追加到结果字符串中。
修复参考代码
#include <iostream> #include <vector> #include <string> int main() { std::vector<int> elements = {1,2,3,4,6}; std::string outputString = "["; for(int i = elements.size() - 1; i >= 0; i--) { // 先将int转为字符串再追加,兼容任意位数的数字 outputString += std::to_string(elements.at(i)); if (i > 0) { outputString.push_back(','); } } outputString.push_back(']'); std::cout << std::endl << outputString << std::endl; return 0; }
运行上述代码即可得到你期望的输出结果[6,4,3,2,1]。
内容的提问来源于stack exchange,提问作者IndiaCharlie
相关产品推荐
相关产品推荐

