程序在C ++中打印最后N行
在本教程中,我们将讨论一个打印最后N行的程序。
为此,我们将提供一个包含新行字符的字符串,以表示下一行的开始以及从最后一行开始要打印的行数。我们的任务是从末尾开始并打印从末尾开始计数的所有N行。
示例
#include <bits/stdc++.h>
using namespace std;
#define DELIM '\n'
//打印最后N行
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;
//找到最后一行的初始位置
target_pos = strrchr(str, DELIM);
if (target_pos == NULL){
cout << "Given string is a single line string";
return;
}
//移到第一行的开始位置
while (cnt < n){
//移至下一行
while (str < target_pos && *target_pos != DELIM)
--target_pos;
if (*target_pos == DELIM)
--target_pos, ++cnt;
//如果字符串少于10行,则中断
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
热门推荐
10 爸妈金婚文案祝福语简短
11 升职加薪的祝福语简短
12 天仙配简短祝福语
13 立冬祝福语简短给女孩
14 每年春节祝福语大全简短
15 厂庆祝福语大全简短
16 过年红包祝福语简短霸气
17 客户新房祝福语简短大气
18 事业祝福语简短网名