一个 C++ 程序用于打印末尾 N 行


本教程中,我们将讨论一个用于打印末尾 N 行的程序。

为此,我们将提供一个字符串,其中包含代表下一行开头的换行符和要从末尾打印的行数。我们的任务是从末尾开始,从末尾数起打印所有 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

更新于: 02-Jan-2020

292 次浏览

提升您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.