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 (const TableRow& row : table->rows()) {
int id = row.getInt("id");
std::string species = row.getString("species");
std::string name = row.getString("name");
println(name, " (", species, ") has ID ", id);
}
saveTable(table, "data/new.csv");
delete table;
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 ", 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];
size_t 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
Use the C++ standard conversion functions. They throw std::invalid_argument when the text does not
start with a number and std::out_of_range when the result does not fit.
int i = std::stoi("42"); // string -> int
float f = std::stof("3.14"); // string -> float
std::string s = std::to_string(frameCount); // number -> string
std::string p = nf(frameCount, 4); // zero-padded: "0042"
For output containing mixed types, pass separate arguments to println() as above, or use Umfeld’s
str() helper: std::string label = str("row ", i);. Do not add a number directly to a string
literal; in C++, "row " + i is pointer arithmetic, not concatenation.