Skip to content

Module 1 · Getting Started with C++ — topic 3 of 3

Basic Syntax and Program Structure

Headers, the std namespace, statements and blocks, comments, input with std::cin and output with std::cout, and the rules for identifiers and keywords.

Beginner 14 min read·Lesson 3 of 40 in C++ Programming

Learning objectives

  • Read and write the basic structure of a C++ program
  • Use std::cin and std::cout for input and output
  • Use using-declarations responsibly

Definition

A C++ program is a set of declarations and definitions spread over translation units; execution begins in the global function main. Standard library facilities are made available with #include and live in namespace std.

Introduction

C++ syntax looks like C: statements end with semicolons, blocks use braces, and comments use // or /* */. The differences appear in how you do input/output and organise names.

Instead of printf and scanf, C++ uses streams. std::cin >> x reads a value of whatever type x is; std::cout << x prints it. The compiler picks the right conversion from the type, so there are no format specifiers to get wrong.

Why it matters

Type-safe streams remove an entire class of C bugs (wrong %d/%lf).

Understanding namespaces explains the std:: prefix you will see everywhere and why using namespace std; in headers is discouraged.

Detailed explanation

#include <iostream> brings in std::cin, std::cout and std::cerr. #include <string> brings in std::string.

std::cin >> a >> b; reads whitespace-separated values. After a failed read, std::cin enters a fail state; test it with if (std::cin >> x) or if (!std::cin).

std::getline(std::cin, line) reads a whole line including spaces. Mixing >> and getline requires discarding the leftover newline with std::cin.ignore() or std::ws.

A using-declaration such as using std::cout; imports one name. using namespace std; imports every name in std; it is acceptable in small .cpp examples but should never appear in a header, where it would affect every file that includes it.

Syntax

C++
#include <iostream>
#include <string>
int main() {
int age;
std::string name;
std::cin >> name >> age;
std::cout << name << " is " << age << '\n';
}
  • >> extracts from an input stream; << inserts into an output stream.
  • std::string grows automatically; no buffer size is needed.
  • Reaching the end of main returns 0 automatically.

Code examples

Reading two values

C++
#include <iostream>
int main() {
int a, b;
std::cin >> a >> b;
std::cout << a << " + " << b << " = " << a + b << '\n';
return 0;
}
Input
12 30
Output
12 + 30 = 42

Reading a full line

C++
#include <iostream>
#include <string>
int main() {
std::string city;
std::getline(std::cin, city);
std::cout << "[" << city << "] has " << city.size() << " characters\n";
return 0;
}
Input
New Delhi
Output
[New Delhi] has 9 characters

More examples

Validating input and mixing >> with getline

C++
#include <iostream>
#include <string>
int main() {
int roll;
std::cout << "Roll: ";
if (!(std::cin >> roll)) {
std::cout << "\nnot a number\n";
return 1;
}
std::string name;
std::cout << "\nName: ";
std::getline(std::cin >> std::ws, name); // skip the leftover newline
std::cout << "\n" << roll << ": " << name << '\n';
return 0;
}
Input
42
Asha Rao
Output
Roll: 
Name: 
42: Asha Rao

Step-by-step explanation

  • if (!(std::cin >> roll)) checks that an integer was actually read.
  • After reading 42 the newline is still in the input.
  • std::cin >> std::ws discards whitespace, so getline reads "Asha Rao" rather than an empty line.
  • The final line prints both values.

Expected output

Running “Validating input and mixing >> with getline” with the sample input shown prints exactly:

TextInput
42
Asha Rao
TextOutput
Roll:
Name:
42: Asha Rao

Practical applications

  • Command-line tools read configuration with streams.
  • Competitive programming solutions read input with cin >>.
  • Log output goes to std::cerr so it isn't mixed with normal output.

Best practices

  • Check stream state after reading input.
  • Prefer std::string and std::getline for text.
  • Keep using namespace std; out of headers.

Common mistakes

getline after >> returns an empty string

Avoid

std::cin >> age;
std::getline(std::cin, name);

Prefer

std::cin >> age;
std::getline(std::cin >> std::ws, name);

>> leaves the newline in the stream; getline stops at it immediately.

using namespace std in a header

Avoid

// util.hpp
using namespace std;

Prefer

// util.hpp
#include <string>
std::string trim(const std::string& s);

It pollutes the namespace of every file that includes the header and can cause name clashes.

Important notes

  • For fast input in competitive programming, std::ios::sync_with_stdio(false); std::cin.tie(nullptr); speeds up streams.
  • C++23 adds std::print and std::println, which use format strings like Python.

Key takeaways

  • Streams: std::cin >> reads, std::cout << prints.
  • Use getline for lines and std::ws to skip leftover newlines.
  • Names in the standard library are in namespace std.

Try it yourself

  1. 1
    Read a full name and a CGPA, then print "<name> has CGPA <cgpa>" with two decimals using <iomanip>'s std::fixed and std::setprecision(2).
  2. 2
    Keep reading integers until the input ends and print their sum.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

4 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerIn `std::cout`, what does `std::` mean?
  • BeginnerGiven the input `12 30`, what is printed?
  • BeginnerAfter `std::cin >> age;`, a following `std::getline(std::cin, name);` returns an empty string. Why?
Practise this topic