Syntax and I/O
โ Report an issue with this lesson#include <iostream>
#include <string>
int main() {
std::string name = "Ada";
int age = 28;
std::cout << name << " is " << age << " years old\n";
return 0;
}
std::string is a real, safe string type -- unlike raw C
strings, it manages its own memory and knows its own length. You can
concatenate with +, compare with ==, and index
with [] without ever touching a null terminator by hand:
std::string first = "Course: ";
std::string title = "C++ Mastery";
std::string full = first + title; // concatenation
bool matches = (title == "C++ Mastery"); // true
char firstChar = title[0]; // 'C'
size_t len = title.length(); // 11
C++ has several ways to read input, and choosing the right one avoids
a classic beginner trap. std::cin >> someInt reads a
single whitespace-delimited token; std::getline(std::cin, someString)
reads an entire line including spaces:
int age;
std::cin >> age; // reads up to the next whitespace
std::cin.ignore(); // consume the leftover newline
std::string fullName;
std::getline(std::cin, fullName); // now reads the rest of the line correctly
Forgetting that leftover newline after a std::cin >> x
is one of the most common C++ input bugs -- the next
std::getline call appears to silently do nothing because it
immediately reads the empty leftover line.
Formatting output precisely often requires <iomanip>.
By default, std::cout prints doubles with up to 6
significant digits and trims trailing zeros, which is rarely what you
want for currency:
#include <iomanip>
double price = 29.9;
std::cout << std::fixed << std::setprecision(2) << price; // 29.90
std::fixed switches to fixed-point notation and
std::setprecision(2) fixes exactly two digits after the
decimal point -- together they're the standard idiom for printing
money-like values consistently.
Try it yourself
Run your code and get it working before marking this lesson complete.
9 more lessons โ including Capstone project: a course catalog manager โ plus a certificate are waiting.
Unlock the full course โ $149.99