如何在写入文件时擦除最后一个逗号

How to erase last comma when writing to a file

本文关键字:擦除 最后一个 文件      更新时间:2023-10-16

我使用以下代码片段将值写入.txt文件:

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

这将生成一个列表,如下所示:20,30,40,50,

我的问题是,如何消除列表中的最后一个逗号?

尝试这样做

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();

您可以为除最后一个元素之外的所有元素写出逗号,然后编写最后一个元素:

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