IntermediateLesson 8 of 18
Input, Files and Streams – C++
Reading from the console, writing and reading files, splitting text with stringstream.
Input and output work through streams: std::cin/std::cout for the console, std::ifstream/std::ofstream for files. All streams work the same way – you write with << and read with >> or std::getline.
#include <fstream>
#include <iostream>
#include <string>
int main() {
{
std::ofstream out("notizen.txt");
out << "Line 1\nLine 2\n";
} // the file is closed automatically at the end of the block (RAII)
std::ifstream in("notizen.txt");
if (!in) {
std::cerr << "File not found\n";
return 1;
}
std::string zeile;
while (std::getline(in, zeile))
std::cout << zeile << '\n';
}You read keyboard input with std::cin. Always check whether reading succeeded. After >>, the newline stays in the buffer – before a following getline, you have to discard it.
std::string name;
int alter = 0;
std::cout << "Name: ";
std::getline(std::cin, name); // whole line including spaces
std::cout << "Age: ";
if (std::cin >> alter) {
std::cout << name << " is " << alter << " years old\n";
} else {
std::cout << "That wasn't a number\n";
}With std::istringstream and std::ostringstream, you treat strings like streams – ideal for splitting and assembling. <filesystem> (C++17) provides platform-independent paths.
#include <filesystem>
#include <iostream>
#include <sstream>
namespace fs = std::filesystem;
int main() {
std::istringstream ss("3 4 5");
int n = 0, summe = 0;
while (ss >> n) summe += n;
std::cout << summe << '\n'; // 12
std::ostringstream os;
os << "x=" << 42 << ", y=" << 3.5;
std::cout << os.str() << '\n'; // x=42, y=3.5
fs::path p = fs::path("daten") / "datei.txt";
std::cout << p.extension().string() << '\n'; // .txt
}TipYou do not have to close files manually: the destructor of
ifstream/ofstream takes care of that. This is RAII – resources are tied to the lifetime of an object.