C++ - 将 Vector 值分配给 std::string 而不会丢失数据

标签 c++ string

我想将一个 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/

相关文章:

c++ - 检查对象类型真的总是糟糕设计的标志吗?

c++ - 你能帮我分析一下这段代码实际上在做什么吗?如果 ((a = b > c ? d : e) == e) a++;

C++ 多个 cin.get()

java - 使用 Java 从美国地址解析邮政编码

ruby - 转义的 Ruby 正则表达式在用作文字正则表达式时不匹配。为什么?

c++ - 模板参数列表中的类型名称是什么意思?

c++ - cpp dll中c静态库的功能

c++ - 如何在 Ray Tracer 中实现景深?

php - 对齐字符串中的两个值 (PHP)

c++ - 以二进制方式将字符串写入文件