C - 将向量值分配给std :: String而不会丢失数据

C++ - assign Vector value to std::string without losing data

本文关键字:String 数据 std 向量 分配      更新时间:2023-10-16

我想将int矢量的值分配给std ::字符串以传递到另一个函数,因为我现在写了此代码:

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

您实际上不需要尝试实现的数据附加副本:

std::string output;
while(input) {
    output += (input % 2 ? "1" : "0");
    input /= 2;
}
std::reverse(std::begin(output), std::end(output));
std::cout << output;

我想按顺序将int矢量的值分配给std :: string 要将其传递到另一个功能,现在我编写了此代码:

您的问题是整数可隐式转换为char。代码output += *it;有效地暗示了类似的内容:

char& i = *it;
i = 1; //Compiles, but how is 1 represented (1 != '1')
 //considering encoding etc?

我以功能方法对此进行了刺伤。您只需用std :: ostringstream实例替换std :: cout并获取其字符串。

#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
int main() {
    std::cout << "Insert the value to convert: t";
    std::vector<int> rem;
    // Get user input...
    std::copy_if(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
        std::back_inserter(rem), [](int val) {return val != 0;});
    //Do your transforation
    std::transform(rem.begin(), rem.end(), rem.begin(), [](int i){return i % 2; });
    //And reverse and copy to stream...     
    std::reverse(rem.begin(), rem.end());
    std::copy(rem.begin(), rem.end(), std::ostream_iterator<int>(std::cout, " "));
}

注意:我同意其他两个答案,但也认为这个答案突出了这个问题。