I am writing a simple CSV export of data using QTextStream but a redundant comma appears at the end of each row. How can I delete the last written symbol in the QTextStream and continue writing data after deleting?
Asked
Active
Viewed 423 times
1
-
This sounds like an XY problem. There is no way to erase a character once it has been written into a stream. You need to add a condition to the loop to check for the last column or a similar check to prevent the comma from being written. – iksemyonov Nov 06 '17 at 10:49
-
Some of the fields are written conditionally and there is no way to know if the next field will be written or not, so no way to know whether to write a separator or not. – Uga Buga Nov 06 '17 at 10:53
-
Can you just write the comma before the field... so stream << "," << nextfield; Then you just have to know if the field is the first one... – FloIsAwsm Nov 06 '17 at 10:59
-
If there is no way to know if the field will be written or not then there is also no way to know if the field is the first one or not. – Uga Buga Nov 06 '17 at 11:27
-
something akin to [ostream_joiner](http://en.cppreference.com/w/cpp/experimental/ostream_joiner)? – Caleth Nov 06 '17 at 12:40
2 Answers
1
The short answer is you can't, it's a stream (without some buffer manipulation I don't think you want to do). There is no such thing as deleting a character - it was already sent "downstream" (think terminal).
You probably want to delete the redundant comma in the original file, or else read the CSV line by line and strip the comma before writing it to the output stream. You can still use QTextStream as an input stream to read line by line, but you would have to strip the comma yourself, before passing it to the output stream.

kabanus
- 24,623
- 6
- 41
- 74
1
There's no stream operation "unwrite", so you can't directly remove the comma. What you should do is ensure that you don't write it.
struct QStreamJoiner
{
QTextStream & ts;
bool doComma = false;
template<typename T>
QStreamJoiner & operator<<(const T & value)
{
if (doComma++) ts << ',';
ts << value;
return *this;
}
}
You can use a wrapper like QStreamJoiner
around your QTextStream
for each line, e.g.
QTextStream out = ...;
for (auto record : records)
{
QStreamJoiner joiner(out);
joiner << record.field1;
if (condition) joiner << record.field2;
...
}

Caleth
- 52,200
- 2
- 44
- 75