इस ट्यूटोरियल में, हम अंतिम N लाइन को प्रिंट करने के लिए एक प्रोग्राम पर चर्चा करेंगे।
इसके लिए, हमें एक स्ट्रिंग प्रदान की जाएगी जिसमें अगली पंक्ति की शुरुआत और अंतिम से मुद्रित होने वाली पंक्तियों की संख्या को दर्शाने के लिए नई पंक्ति वर्ण शामिल होगा। हमारा काम आखिरी से शुरू करना और आखिरी से गिनती करते हुए सभी एन लाइनों को प्रिंट करना है।
उदाहरण
#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;
} आउटपुट
str12 str13 str14 str15 str16 str17 str18 str19 str20 str21 str22 str23 str24 str25