How to erase last comma when writing to a file

Viewed 81

I'm using the following snippet to write values to a .txt file:

fstream f1;
f1.open("output.txt", ios::out);
{
    for (const auto& avg : clusAvg)
    {
        f1 << avg << ",";
    }
}
f1.close();

This generates a list that looks like: 20,30,40,50,

My question is, how can I eliminate that last comma in the list?

2 Answers

Try doing this

fstream f1;
f1.open("output.txt", ios::out);
{
    bool first = true;
    for (const auto& avg : clusAvg)
    {
        if(!first) f1 << ", ";
        first = false;

        f1 << avg;
    }
}
f1.close();

You can write out a comma for all but the last element, and then write the last element:

if (! clusAvg.empty())
{
  for (auto i = 0u; i < clusAvg.size() - 1; ++i)
    f1 << clusAvg[i] << ", ";
  f1 << clusAvg.back();
}
Related