I'm trying to turn a vector<int> into a string, with a '[' at the beginning, and a ',' between each element of the vector, and a ']' at the end. But my output is [,,,,] (wanted output [6,4,3,2,1]).
Can you explain to me what i'm doing wrong?
Here's what I tried:
int main() {
std::vector<int> elements = {1,2,3,4,6};
std::string outputString = "[";
for(int i = elements.size() - 1; i >= 0; i--) {
if (i > 0) {
outputString.push_back(elements.at(i));
outputString.push_back(',');
}
else {
outputString.push_back(elements.at(i));
}
}
outputString.push_back(']');
std::cout << std::endl << outputString << std::endl;
}
CodePudding user response:
std::string::push_back adds a single char to the string and you tripped over the implicit conversion of int to char. The low values correspond to non-printable characters, thats why you don't see them in the output.
You can use operator = and std::to_string:
#include <vector>
#include <string>
#include <iostream>
int main() {
std::vector<int> elements = {1,2,3,4,6};
std::string outputString = "[";
for(int i = elements.size() - 1; i >= 0; i--) {
if (i > 0) {
outputString = std::to_string(elements.at(i));
outputString.push_back(',');
}
else {
outputString = std::to_string(elements.at(i));
}
}
outputString.push_back(']');
std::cout << std::endl << outputString << std::endl;
}
PS: I didn't even know that std::string::push_back exists. You can also use operator = to add a single character to the string.
CodePudding user response:
You are adding the integers as-is to the string, implicitly converting them to single characters. Most characters with values below 32 are non-printable. You need to convert the integers to strings, such as with std::to_string().
outputString = std::to_string(elements[i]);
Another way to implement this is to use std::ostringstream instead, let operator<< handle the conversion for you, eg:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
std::string vector_to_string_in_reverse(const std::vector<int> &elements)
{
std::ostringstream outputStream;
outputStream << '[';
if (!elements.empty()) {
auto it = elements.crbegin(), end = elements.crend();
outputStream << *it ;
while (it != end) {
outputStream << ',' << *it ;
}
}
outputStream << ']';
return outputStream.str();
}
int main() {
std::vector<int> elements = {1,2,3,4,6};
std::cout << std::endl << vector_to_string_in_reverse(elements) << std::endl;
}
