zDoes
zDoes

Reputation: 63

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

I want to assign the value of a int vector to a std::string in order to pass it to another function, for now i wrote this code:

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

The problem with my code is that the string contains weird characters like ☺ ☺☺☺ ☺☺☺☺ ☺...is there any way to prevent that?

Upvotes: 0

Views: 539

Answers (3)

Werner Erasmus
Werner Erasmus

Reputation: 4076

I want to assign the value of a int vector to a std::string in order to pass it to another function, for now i wrote this code:

Your problem is that an integer is implicitly convertible to char. The code output += *it; effectively implies something similar to:

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

I've taken a stab at it with functional approach. You can just replace std::cout in the end with a std::ostringstream instance and get its string.

#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, " "));
}

NOTE: I agree with both other answers, but also feel this answer highlights the issue.

Upvotes: 0

zen-cat
zen-cat

Reputation: 425

You don't actually need an additional copy of your data for what you are trying to achieve:

std::string output;
while(input) {
    output += (input % 2 ? "1" : "0");
    input /= 2;
}

std::reverse(std::begin(output), std::end(output));

std::cout << output;

Upvotes: 2

rakibdana
rakibdana

Reputation: 39

Why you are not converting int to string while adding to output? Try this:

    std::stringstream ss;
    ss << *it;

    std::string str = ss.str();
    output += str; //Assign every value of the iterator to string variable

Upvotes: 2

Related Questions