In C++, what is the simplest way to convert a vector of ints (i.e. vector<int>
) to a string ?
Using stoi() function Starting with C++11, you can use the stoi function to convert a string to an int, defined in the <string> header file. It throws std::invalid_argument if the string cannot be parsed. However, it can extract the integer value 1 from the strings like 1s .
I usually do it this way...
#include <string> #include <vector> int main( int argc, char* argv[] ) { std::vector<char> vec; //... do something with vec std::string str(vec.begin(), vec.end()); //... do something with str return 0; }
Maybe std::ostream_iterator
and std::ostringstream
:
#include <vector> #include <string> #include <algorithm> #include <sstream> #include <iterator> #include <iostream> int main() { std::vector<int> vec; vec.push_back(1); vec.push_back(4); vec.push_back(7); vec.push_back(4); vec.push_back(9); vec.push_back(7); std::ostringstream oss; if (!vec.empty()) { // Convert all but the last element to avoid a trailing "," std::copy(vec.begin(), vec.end()-1, std::ostream_iterator<int>(oss, ",")); // Now add the last element with no delimiter oss << vec.back(); } std::cout << oss.str() << std::endl; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With