

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to print last 10 lines in C++
In this tutorial, we will be discussing a program to print the last 10 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. Our task is to start from the last and print all the 10 lines counting from the last.
Example
#include <bits/stdc++.h> using namespace std; #define DELIM '\n' //printing the last 10 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, 10); return 0; }
Output
str16 str17 str18 str19 str20 str21 str22 str23 str24 str25
- Related Questions & Answers
- Program to print last N lines in c++
- Python program to print palindrome triangle with n lines
- How to select last 10 rows from MySQL?
- How to print multiple blank lines in C#?
- How to plot the lines first and points last in Matplotlib?
- 8085 Program to Exchange 10 bytes
- Python program to print the initials of a name with last name in full?
- Java program to print the initials of a name with last name in full
- Python Program to Print Nth Node from the last of a Linked List
- How can we print multiple blank lines in python?
- JavaScript code to print last element of an array
- Print the last occurrence of elements in array in relative order in C Program.
- Java program to delete duplicate lines in text file
- Program to find how many lines intersect in Python
- Java Program to replace the first 10 characters in JTextArea
Advertisements