如何在写入文件时擦除最后一个逗号
How to erase last comma when writing to a file
我使用以下代码片段将值写入.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();
}
相关文章:
- 引用一个已擦除类型(void*)的指针
- 如何在写入文件时擦除最后一个逗号
- std::字符串擦除以删除最后一个字母
- 有没有办法访问除最后一个模板参数之外的所有内容
- 无法使用擦除方法删除矢量的最后一个元素
- 如果地图擦除范围内的第一个和最后一个相等,则是否删除该元素
- 如何在下一次函数调用中使用 STL 映射擦除从最后一个位置
- 使用索引向量擦除另一个向量的索引
- 正在擦除文件中的最后一个输入
- 将除最后一个作为变量类型的变量外的所有可变模板参数解包
- std::map - 擦除最后一个元素
- 将空格字符添加到附加的每个项目,以必须擦除最后一个项目.如何改进
- 用作 std::multimap 擦除范围的第一个和最后一个的递增迭代器
- std::vector push_back()擦除上一个元素
- vector::erase不会擦除所需的元素,而是从向量中擦除最后一个元素
- 从std::cout中擦除最后一个值
- 保持文本文件从擦除在一个函数,但保持能力写到它?c++
- 擦除 std::set 的最后一个成员
- 获取变量模板的除最后一个参数外的所有参数
- std::string擦除最后一个字符失败