-1

Here is my code. I tried to print the content of a vector with a comma after each element as the separator. How can I delete the comma after the last element then?

#include <iostream>
#include <vector>
#include <string>
using namespace std;
void printShoppingList(vector<string> s)
{
    for (auto i = s.begin(); i != s.end(); ++i)   //iterate vector from start to end
        cout<< *i<<", ";              //print each item from vector
}

cuz for now my output is like

Items: eggs, milk, sugar, chocolate, flour,

with a comma at the end.

Please help to delete the comma at the end of the output.

JHBonarius
  • 10,824
  • 3
  • 22
  • 41
Janet
  • 9
  • 2

1 Answers1

0

You have access to the iterator inside the loop, so you can check that:

    for (auto i = s.begin(); i != s.end(); ++i) {
        cout << *i;
        if (i + 1 != s.end()) { std::cout <<", "; }
    }

Alternatively, you might put the comma before the elements (besides the first element):

    for (auto i = s.begin(); i != s.end(); ++i) {
        if (i != s.begin()) { std::cout <<", "; }
        cout << *i;
    }

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
lorro
  • 10,687
  • 23
  • 36