New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› C++› Variables, Types and Input

Variables, Types and Input

💻 C++

Store numbers and text, read input and format output.

Lesson 2 of 9 Tutorial
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

  1. Read two numbers and print their sum.
  2. Read a full name with spaces.
  3. 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
Expected Output
A line such as: Amina Bello (16) scored 78.5

Lesson Nav

Lesson sections