Answer to Question #278144 in C++ for zain

Question #278144

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. 


1
Expert's answer
2021-12-12T01:19:11-0500


#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog