I am just starting to use C++ iterators, so this code may be very bad compared to experienced programmers, but I would love all help because I am trying to get better with them. In this function, I am attempting to use a reverse iterator's position to add a comma in between each 3 letters of a number. Ex: 100000 to 100,000.
I was able to fix all errors and warnings, but the code wont output anything. It also says that I have a SIGTRAP that my program received. Please help me.
#include <iostream>
#include <vector>
#include <iterator>
#include <string>
using namespace std;
int main() {
string text = "100000";
vector<char> news{};
for (size_t i{}; i < text.size(); i++) {
news.push_back(text[i]);
}
for (vector<char>::reverse_iterator it = news.rbegin(); it != news.rend(); it = it + 2) {
news.insert(it.base(), ',');
}
string fin;
for (char i: news)
fin.push_back(i);
cout << fin;
return 0;
}
You don't want to try to mutate a collection while iterating over it. The instant you do that you invalidate your iterators.
Rather we'll iterate over
textin reverse and build up atext2string. Then we need to reverse that string.