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;
}
outputString.push_back(elements.at(i));does? Do you understand the difference between1and'1'?std::ostringstreamfor this task