Hi I am outputting data to a spreadsheet and have looped through one set of values.
Later on I want to put some more values in the next column, I can move across to the next column but don't know how to get back to the top. Is this possible to do?

Dani AI

Generated

Short answer: you cannot reliably "seek back to the top" of a plain CSV and insert values, because CSV is a linear text format and earlier lines change length when you insert text. As suggested, it is possible to achieve the effect — but only by building the final rows/columns first (in memory or via temp files) or by using a real spreadsheet API that writes specific cells.

Two safe approaches:

  1. Build a 2D table in memory, then write the CSV once. This is simplest when the data set fits memory. Store values by row/column, escape fields (double quotes inside fields become two quotes; wrap fields that contain commas/quotes/newlines), then stream rows to disk.
#include <vector>
#include <string>
#include <fstream>

// simple CSV escape: quote when needed, double inner quotes
std::string escape(const std::string &s) {
    if (s.find_first_of(",\"\n") == std::string::npos) return s;
    std::string out = "\"";
    for (char c : s) if (c == '"') out += "\"\""; else out += c;
    out += "\"";
    return out;
}

// fill table[row][col] as you produce values, then write:
std::vector<std::vector<std::string>> table(rows, std::vector<std::string>(cols));
std::ofstream out("out.csv");
for (auto &r : table) {
  for (size_t i = 0; i < r.size(); ++i) {
    if (i) out << ',';
    out << escape(r[i]);
  }
  out << '\n';
}
  1. Stream-safe (low memory): write each logical column to its own temporary file as you produce it. After all columns are created, open all temp files and read them line-by-line, joining fields into final CSV rows. This merges columns without holding everything in RAM.

If you must update arbitrary cells in place, use a spreadsheet library or the native format (XLSX/ODS) or design a fixed-width text format. Also remember CSV pitfalls: quoting, CR/LF differences on platforms, and uneven row counts when merging temp files. These are the practical, robust ways to "start a new column and go back to the top" for CSV output.

Recommended Answers

All 2 Replies

Member Avatar for Member #46692

I don't see why not.

I don't see why not.

Okay , any hints?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.