
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Program to print last N lines in c++
In this tutorial, we will be discussing a program to print the last N lines.
For this, we will be provided with a string that consists of the new line character to denote the start of the next line and the number of lines to be printed from the last. Our task is to start from the last and print all the N lines counting from the last.
Example
#include <bits/stdc++.h> using namespace std; #define DELIM '\n' //printing the last N lines void print_last_lines(char *str, int n){ if (n <= 0) return; size_t cnt = 0; //storing the number of lines char *target_pos = NULL; //finding the initial position of last line target_pos = strrchr(str, DELIM); if (target_pos == NULL){ cout << "Given string is a single line string"; return; } //moving to the start position of the 1st line while (cnt < n){ //moving to the next lines while (str < target_pos && *target_pos != DELIM) --target_pos; if (*target_pos == DELIM) --target_pos, ++cnt; //if string has less than 10 lines the break else break; } if (str < target_pos) target_pos += 2; cout << target_pos << endl; } int main(void){ char *str1 ="str1\nstr2\nstr3\nstr4\nstr5\nstr6\nstr7\nstr8\nstr9” "\nstr10\nstr11\nstr12\nstr13\nstr14\nstr15\nstr16\nstr17" "\nstr18\nstr19\nstr20\nstr21\nstr22\nstr23\nstr24\nstr25"; print_last_lines(str1, 14); return 0; }
Output
str12 str13 str14 str15 str16 str17 str18 str19 str20 str21 str22 str23 str24 str25
- Related Articles
- Program to print last 10 lines in C++
- Python program to print palindrome triangle with n lines
- Remove the Last N Lines of a File in Linux
- How to print multiple blank lines in C#?
- Program to find last two digits of 2^n in C++
- Python Program to Read First n Lines of a File
- Java program to print the initials of a name with last name in full
- Python program to print the initials of a name with last name in full?
- Program to print ‘N’ alphabet using the number pattern from 1 to n in C++
- Python program to print check board pattern of n*n using numpy
- Python program to print a checkboard pattern of n*n using numpy.
- Python Program to Print Nth Node from the last of a Linked List
- How to plot the lines first and points last in Matplotlib?
- Print the last occurrence of elements in array in relative order in C Program.
- Recursive program to print formula for GCD of n integers in C++

Advertisements