All chapters
Cookbook · Chapter 4

Working with data

Text files, CSV tables, XML, and the C++ stand-ins for Processing's String, array, ArrayList and HashMap.

Loading text files

loadStrings() reads a file into a vector of lines; saveStrings() writes one back. Keep data files in a data/ folder next to the sketch.

std::vector<std::string> lines = loadStrings("poem.txt");
for (const std::string& line : lines) {
    println(line);
}
saveStrings("out.txt", lines);

Parsing CSV

loadTable() parses comma-separated values. Pass "header" when the first row holds column names, then read typed cells from each row:

Table* table = loadTable("mammals.csv", "header");
println(table->getRowCount() + " rows");

for (TableRow row : table->rows()) {
    int    id      = row.getInt("id");
    String species = row.getString("species");
    String name    = row.getString("name");
    println(name + " (" + species + ") has ID " + id);
}

saveTable(table, "data/new.csv");

Parsing XML

XML xml;

void setup() {
    xml = loadXML("data.xml");
    // walk children and read attributes / content
}

The C++ stand-ins for Java collections

Coming from Processing, the data types you reach for change names — the C++ standard library already has them. This is the one place the translation is not one-to-one.

Processing (Java) Umfeld (C++)
String std::string (String is also available)
int[], float[] std::vector<int>, std::vector<float>
ArrayList<T> std::vector<T>
HashMap<K, V> std::unordered_map<K, V>

Strings

std::string name = "umfeld";
println(name + " has " + to_string(name.length()) + " letters");
println(name.substr(0, 3));               // "umf"

Arrays and ArrayLists — std::vector

std::vector<float> xs;
xs.push_back(mouseX);          // grow like an ArrayList
float first = xs[0];
int   n     = xs.size();

for (float x : xs) {
    point(x, height / 2);
}

HashMaps — std::unordered_map

#include <unordered_map>

std::unordered_map<std::string, int> counts;
counts["red"]  = 3;
counts["blue"] += 1;

for (const auto& [key, value] : counts) {
    println(key, "=", value);
}

Converting datatypes

int   i = int("42");                 // string -> int
float f = float("3.14");             // string -> float
std::string s = to_string(frameCount); // number -> string
std::string p = nf(frameCount, 4);     // zero-padded: "0042"