Skip to content

Strings and IO

Derek Snider edited this page May 19, 2026 · 1 revision

Strings & I/O

String basics

string s = "hello world";
cout << s << endl;

string is backed by C++ std::string. Strings are mutable and grow automatically.

Output with cout

cout << "hello " << x << endl;
std::cout << "qualified" << std::endl;

Chain multiple values with <<. Works with strings, integers, floats, and char *.

C-style output

puts("hello");              // print string + newline
putchar('h');               // print single character
puti(42);                   // print integer
printf("x = %d\n", x);     // formatted output (via #include <stdio.h>)

Input with cin

string name;
int age;

cout << "Enter name: ";
cin >> name;
cout << "Enter age: ";
cin >> age;
cout << "Hello, " << name << ", age " << age << endl;

cin >> var reads whitespace-delimited tokens from stdin. Works with string, int, and double.

Chained input:

string a;
string b;
cin >> a >> b;

Stringstream

stringstream ss;
ss << "value: " << 42;
string result;
result = ss.str();
cout << result << endl;    // value: 42

File I/O

Writing

ofstream out;
string fname = "output.txt";
out.open(fname);
out << "Hello!" << endl;
out.close();

Reading

ifstream in;
string fname = "output.txt";
in.open(fname);
string line;
while (in.good()) {
    getline(in, line);
    if (in.good())
        cout << line << endl;
}
in.close();

With defer

ofstream out;
string fname = "output.txt";
out.open(fname);
defer out.close();         // auto-close at scope exit
out << "data" << endl;

String operations via namespaces

madc strings can be manipulated with functions from any namespace:

string s = "  Hello, World!  ";

php::trim(s);                    // "Hello, World!"
perl::lc(s);                     // "hello, world!"
python::title(s);                // "Hello, World!"
ruby::squeeze(s);                // collapse duplicates
rust::contains(s, "World");      // 1

string encoded;
js::btoa(encoded, s);            // base64

What's next?

Clone this wiki locally