Variables, Types and Input
💻 C++Store numbers and text, read input and format output.
0 of 9 completed
C++ types are explicit and fixed. Choosing the right one matters for correctness and memory use.
By the end of this lesson you can:
- Declare common types.
- Read input with cin.
- Convert and format values.
Basic Types
int for whole numbers, double for decimals, char for one character, bool for true or false and std::string for text.
#include <string>
int age = 16;
double price = 2500.50;
char grade = 'A';
bool active = true;
std::string name = "Amina";Reading Input
std::cin reads from the keyboard. For a full line with spaces, use std::getline.
#include <iostream>
#include <string>
int main() {
int age;
std::cout << "Age: ";
std::cin >> age;
std::cin.ignore();
std::string name;
std::cout << "Full name: ";
std::getline(std::cin, name);
std::cout << name << " is " << age << " years old.\n";
return 0;
}Formatting
Use std::fixed and std::setprecision for consistent decimal places. Include <iomanip>.
#include <iomanip>
#include <iostream>
std::cout << std::fixed << std::setprecision(2) << 2687.5 << "\n";Warning Mixing cin >> and getline can leave a newline in the input buffer. Call cin.ignore() between them.
Practice
- Read two numbers and print their sum.
- Read a full name with spaces.
- Print a price with two decimal places.
Hands-on exercise
Write a program that reads a name, age and average score, then prints them in a clean format with the score to one decimal place.
Recap
C++ types are explicit. Use cin for tokens, getline for full lines and iomanip for formatted output.
Example
#include <string>
int age = 16;
double price = 2500.50;
char grade = 'A';
bool active = true;
std::string name = "Amina";
Exercises
Exercise 1. Student details
Easy
Write a program that reads a name, age and average score, then prints them in a clean format with the score to one decimal place.
C++
exercise-1.txt
Output
Expected Output
A line such as: Amina Bello (16) scored 78.5
Lesson Nav
Course contents
C++ Course
0/9 lessons completed
- 1 Your First C++ Program Tutorial
- 2 Variables, Types and Input Tutorial
- 3 Conditions and Loops Tutorial
- 4 Functions and Parameters Tutorial
- 5 Arrays and Vectors Tutorial
- 6 Pointers and References Tutorial
- 7 Classes and Objects Tutorial
- 8 The STL: Containers and Algorithms Tutorial
- 9 Project: A Console Grade Book Project
Exercises
Exercise 1 Student details