C++
Text serialization
Learn human-readable format with text serialization.
What is text serialization?
Text serialization writes object data as human readable text. In C++ you use the << (output) operator of std::ofstream. To read back you use the >> (input) operator of std::ifstream.
Example: ofs << name << " " << age; writes a name and age separated by a space. ifs >> name >> age; reads them back. The >> operator reads up to whitespace, so values must be separated by spaces or newlines. Text serialization is slower but can be inspected in a text editor and is good for debugging.
Struct serialization example
To serialize a Person struct as text you first write the fields with <<, putting spaces between them. To read back you read with >> in the same order. Order matters: the write and read order must match.
Example: write side ofs << p.name << " " << p.age;. Read side ifs >> name >> age;. The file contains "Alex 30" and reads back the same. To add another field you append << " " << p.city and on read add >> city. This is simple but order dependent.
Exercise Text serialize a Person struct
Define struct Person { std::string name; int age; };. Set std::string name = "Alex"; and int age = 30;. Write with std::ofstream ofs("person.txt") and ofs << name << " " << age;. Read with std::ifstream ifs("person.txt") and ifs >> loaded_name >> loaded_age;. Print std::cout << loaded_name << " " << loaded_age;.
Show example solution
#include <iostream>
#include <fstream>
#include <string>
struct Person {
std::string name;
int age;
};
int main() {
std::string name = "Alex";
int age = 30;
std::ofstream ofs("person.txt");
ofs << name << " " << age;
ofs.close();
std::string loaded_name;
int loaded_age;
std::ifstream ifs("person.txt");
ifs >> loaded_name >> loaded_age;
ifs.close();
std::cout << loaded_name << " " << loaded_age;
return 0;
}
Test yourself
-
Match the operator to its role
- ofs << value
- Writes text
- ifs >> value
- Reads text
- " " (space)
- Field separator
- std::ofstream
- Output file
-
How does the >> operator read?
- The whole line at once
- Only numbers
- Until the end of file
- Reads up to whitespace
Show answer
Reads up to whitespace — The >> operator reads up to a space or newline.
-
Complete the struct name
struct ____ { std::string name; int age; };
Show answer
struct Person { std::string name; int age; };
Next lesson: JSON library