Basic structure of cout:
cout << “ … “;
Note:
▪ cout -> Character Output
▪ Defined in the <iostream> header file.
▪ The insertion operator (<<)is used to send data to the standard output (on the console).
▪ ‘endl’ is used to insert a newline character and flush the output buffer.
▪ ‘\n’ is simply a newline character without flushing the buffer.
▪ cout is part of the std namespace.
▪ We can either use the full name std::cout or declare using namespace std; to
avoid writing std:: each time.
Hierarchy of cout, endl, cin:
iostream (Header File)
std (Namespace)
ios (Namespace)
ostream (Base class of output stream)
cout, endl
istream (Base class of input stream)
cin
1. Basic structure of cin:
cin << varaibles;
Note:
▪ cin –> Character Input
▪ Defined in the <iostream> header file.
▪ Reads a string without spaces.
▪ The extraction operator (>>) is used to extract values from input streams.
2. Basic structure of getline:
getline(cin, stringVariable);
Note:
▪ Reads a whole line of input, including spaces.
▪ It automatically terminates when it encounters a newline character.
Advanced Usage
1. Reading Characters
cin.get()is used to read a single character, including whitespace.
char ch;
cout << "Enter a character: ";
cin.get(ch);
cout << "You entered: " << ch << endl;
2. Reading Strings with Spaces
getline()is used to read strings that may contain spaces.
string address;
cout << "Enter your address: ";
getline(cin, address);
cout << "Address: " << address << endl;
3. Clearing the Input Buffer
getline() is often paired with cin.ignore() to handle any leftover newline characters in
the buffer.
Syntax:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.ignore(int n, char delim):
• n: The maximum number of characters to ignore.
• delim: The delimiter character at which to stop ignoring. Typically, this is a newline
character ('\n').
#include <iostream>
#include <limits> // Required for numeric_limits
using namespace std;
int main() {
int age;
string name;
cout << "Enter your age: ";
cin >> age;
// User enters 25, but a newline '\n' is left in the buffer
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// Clear the buffer
cout << "Enter your full name: ";
getline(cin, name);
// Now getline() reads the full name, not the leftover newline
cout << "Age: " << age << ", Name: " << name << endl;
return 0;
}
4. Skipping Specific Characters
We might want to skip a certain number of characters or up to a specific character.
char ch;
cout << "Enter a string ending with 'x': ";
cin >> ch; // Assume input is "Hello x"
cin.ignore(100, 'x');
// Ignore up to 100 characters or until 'x' is found
cout << "Remaining input: ";
cin >> ch;
cout << ch << endl;
// Outputs whatever character comes after 'x'
5. By default cin.ignore()
cin.ignore() without arguments will skip one character from the input stream. This is
equivalent to calling cin.ignore(1).
#include <iostream>
using namespace std;
int main() {
char ch;
cout << "Enter a character: ";
cin >> ch;
cout << "You entered: " << ch << endl;
cin.ignore(); // Skips the newline character
cout << "Enter another character: ";
cin >> ch;
cout << "You entered: " << ch << endl;
return 0;
6. Input Validation
If the user enters data that doesn’t match the type of the variable (e.g., entering a letter when
an int is expected), cin will fail, and the variable will not be modified. To handle such cases,
use cin.fail()
int number;
cout << "Enter an integer: ";
cin >> number;
if (cin.fail()) {
cout << "Invalid input, not an integer." << endl;
cin.clear();
// Clear the fail state
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// Ignore bad input
} else {
cout << "You entered: " << number << endl;
}
setprecesion
setprecision is a manipulator in C++ that sets the number of digits to be displayed after the
decimal point when outputting floating-point numbers. It is defined in the <iomanip> header
file.
std::cout << std::setprecision(n);
n: The number of significant digits to display. If used with std::fixed or
std::scientific, it specifies the number of digits after the decimal point.
1. Without std::fixed
Sets the total number of significant digits (both before and after the decimal point).
#include <iostream>
#include <iomanip> // Include header for setprecision
using namespace std;
int main() {
double num = 123.456789;
cout << "Default precision: " << num << endl; // Default precision
cout << "Precision set to 3: " << setprecision(3) << num << endl; // Total
3 significant digits
cout << "Precision set to 5: " << setprecision(5) << num << endl; // Total
5 significant digits
return 0;
Output:
Default precision: 123.457
Precision set to 3: 123
Precision set to 5: 123.46
2. With std::fixed
Sets the number of digits to display after the decimal point.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double num = 123.456789;
cout << fixed; // Use fixed notation for floating-point numbers
cout << "Precision set to 2: " << setprecision(2) << num << endl;
// 2 digits after the decimal point
cout << "Precision set to 4: " << setprecision(4) << num << endl;
// 4 digits after the decimal point
return 0;
Output:
Precision set to 2: 123.46
Precision set to 4: 123.4568
3. Controlling Precision with std::scientific
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double num = 123.456789;
cout << scientific; // Use scientific notation
cout << "Precision set to 2: " << setprecision(2) << num << endl;
// 2 digits after the decimal point
cout << "Precision set to 4: " << setprecision(4) << num << endl;
// 4 digits after the decimal point
return 0;
Output:
Precision set to 2: 1.23e+02
Precision set to 4: 1.2346e+02
Note:
By default, cout prints floating-point numbers with up to 6 digits of precision. We can change
this using setprecision.
• Basic Structure:
• Syntax:
switch (expression) {
case constant1:
// Code to execute for constant1
break;
case constant2:
// Code to execute for constant2
break;
...
default:
// Code to execute if no case matches
}
• Expression Type:
• The expression in a switch statement must be of integer type (e.g., int, char, enum).
• Cannot use floating-point types (float, double) or non-integer types.
• Case Labels:
• case labels must be compile-time constants and of the same type as the expression.
• Each case label must be unique within the same switch statement.
• break Statement:
• Purpose: Terminates the switch statement and exits it.
• Omission: Without break, execution continues to the next case (known as "fall-through").
• Fall-through Behavior: Multiple cases can share the same block of code if break is
omitted.
• Optional default Case:
• The default case is optional.
• It is executed if none of the case values match the expression.
• Can be placed anywhere in the switch block but is usually placed at the end.
• Fall-through Behavior:
• If a case does not end with a break, execution will continue to the next case (even if it
doesn't match).
• Used intentionally to handle multiple cases with shared code.
• Efficiency:
• Generally more efficient than a series of if-else statements.
• Many compilers optimize switch statements using jump tables.
• Nested switch Statements:
• switch statements can be nested inside each other.
• Should be used carefully to avoid complex and difficult-to-read code.
• Limitations:
• case labels must be constant expressions.
• switch expression cannot evaluate to non-integer types.
• Not suitable for complex conditions or ranges (use if-else in such cases).
• Common Use Cases:
• Handling menu-driven programs.
• Processing command-line arguments.
• Managing key events.
• Simplifying multi-way branching where the variable has a limited set of distinct values.
min() and max() are functions used to find the minimum and maximum values, respectively,
from a set of values. These functions are defined in the <algorithm> header.
min() and max() with More Than Two Arguments
1. Directly pass multiple arguments: (Alternative of Initializer list)
#include <iostream>
#include <algorithm> // For std::min
int main() {
int a = 3, b = 7, c = 2, d = 8, e = 5;
int minimum = std::min({a, b, c, d, e});
std::cout << "The minimum value is: " << minimum << std::endl;
return 0;
2. Using initializer lists:
#include <algorithm>
#include <initializer_list>
int main() {
initializer_list<int> values = {10, 5, 8, 12};
int smallest = min(values.begin(), values.end());
int largest = max(values.begin(), values.end());
cout << "Smallest value: " << smallest << endl;
cout << "Largest value: " << largest << endl;
return 0;
}
The swap() function is used to exchange the values of two variables. It's a part of the
<algorithm> header and can be used with various data types, including built-in types, user-
defined types, and even standard library containers.
#include <iostream>
#include <algorithm> // For std::swap
int main() {
int x = 10, y = 20;
std::cout << "Before swap:" << std::endl;
std::cout << "x = " << x << ", y = " << y << std::endl;
std::swap(x, y); // Swapping the values
std::cout << "After swap:" << std::endl;
std::cout << "x = " << x << ", y = " << y << std::endl;
return 0;
cin – like scanf() (Without space and enter)
fgets() – with space, and enter (String size become 1 more, that is the enter input)
getline() – with space, but without enter (String size remains as it is, since it doesn’t take the enter
as input)
Note: Pressing enter means end of the input.
The header file for C and C++ is ‘bits/stdc++.h’. (#include <bits/stdc++.h>)