Write a program that reads lines of text and appends them to a char buffer[1000]. Stop after reading 1,000 characters. As you read in the text, replace all newline characters '\n' with '\0' terminators. Establish an array char* lines[100], so that the pointers in that array point to the beginnings of the lines in the text. Consider only 100 input lines if the input has more lines. Then display the lines in reverse order, starting with the last input line.
#include <iostream>
void read_and_print(){
std::ifstream input("D:\\data.txt");
if (!input.is_open() || !input.good())
return;
char buffer[1001];
int b = 0;
char* lines[100];
int l = 0;
char** e;
bool set_start = false;
lines[l] = buffer + b;
e = lines + (l++);
char t;
while (input.get(t) && b < 1000)
{
if (set_start)
{
if (l < 100) {
lines[l] = buffer + b;
e = lines + l;
}
l++;
set_start = false;
}
if (t == '\n') {
t = '\0';
set_start = !set_start;
}
buffer[b] = t;
b++;
}
input.close();
if (b == 1000)
buffer[1000] = '\0';
else if (b < 1000)
buffer[b] = '\0';
while (lines <= e) {
std::cout << *e << std::endl;
e--;
}
}
int main(){
read_and_print();
return 0;
}
Comments
Leave a comment