How to turn an integer into vector and then turn that vector into string in C++
Solution 1:
The easiest is : std::to_string(yourNum);
If you do need the steps:
std::vector<int> res;
int num;
std::cin >> num;
while(num>0)
{
res.insert(res.begin(),num%10);
num/=10;
}
and then
std::stringstream result;
std::copy(res.begin(), res.end(), std::ostream_iterator<int>(result, ""));
Solution 2:
Since you insist on placing the integers in a vector first and then converting them to string later (when needed?), this can be a solution:
#include <iostream>
#include <string>
#include <vector>
int main( )
{
std::string number;
std::cin >> number;
std::vector<int> numbers;
numbers.reserve( number.length( ) );
for ( const auto digit : number )
{
numbers.push_back( digit - '0' );
}
std::cout << "\nElements of vector: ";
for ( const auto digit : numbers )
{
std::cout << digit << ' ';
}
std::cout << "\nElements of vector converted to `std::string`: ";
for ( const auto num : numbers )
{
std::string num_str { std::to_string( num ) };
std::cout << num_str << ' ';
}
std::cout << '\n';
}
Sample I/O:
1234
Elements of vector: 1 2 3 4
Elements of vector converted to `std::string`: 1 2 3 4
Solution 3:
Here you are:
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <algorithm>
#include <iterator>
int main() {
int n;
std::cin >> n;
std::vector<int> split(static_cast<int>(std::log10(n)) + 1);
auto royal_10 = split.rbegin();
auto cpy{ n };
do {
*royal_10++ = cpy % 10;
} while ((cpy /= 10) != 0);
std::string ret;
ret.reserve(split.size());
std::transform(split.cbegin(), split.cend(), std::back_inserter(ret),
[](int const dig) { return dig + '0'; });
return 0;
}