Text serialization
- C++ course
- Advanced
- Lesson 50/83
- 5 min
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.
Practice 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;.
Starter code
#include <iostream>
#include <fstream>
#include <string>
// Define the Person struct, write to file and read back
int main() {
// Add the ofs and ifs calls
return 0;
}Sample 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;
}Expected output
Alex 30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the operator to its role
| Term | Meaning |
|---|---|
ofs << value |
Writes text |
ifs >> value |
Reads text |
" " (space) |
Field separator |
std::ofstream |
Output file |
2 How does the >> operator read?
- The whole line at once
- Only numbers
- Until the end of file
- Reads up to whitespace Correct answer
Explanation: The >> operator reads up to a space or newline.
3 Complete the struct name
struct ____ { std::string name; int age; };
struct Person { std::string name; int age; };
Explanation: The Person struct holds a name and age field.