Answer to Question #280578 in C++ for Adnan

Question #280578

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-17T06:52:30-0500
#include <iostream>


using namespace std;


const int BUFFER_SIZE = 1000;
const int LAST_LINES_SIZE = 100;


int findNullCharReverse(char* buffer, int from) {
    int pos = -1;


    for (int i = from; i >= 0; i--) {
        if (buffer[i] == '\0') return i;
    }


    return pos;
}


int findLastLines(char* buffer, char* lines[]) {
    int linesCount = 0;
    int end = BUFFER_SIZE - 1;
    int i2;


    for (int i = 0; i < LAST_LINES_SIZE; i++) {
        int start = findNullCharReverse(buffer, end - 1);
        lines[linesCount] = new char[end - start];


        i2 = 0;


        for (int j = start + 1; j <= end; j++) {
            lines[linesCount][i2] = buffer[j];
            i2++;
        }


        linesCount++;
        end = start;
        if (start == -1) break;
    }


    return linesCount;
}


void replaceNewLineChars(char* buffer) {
    for (int i = 0; i < BUFFER_SIZE; i++) {
        if (buffer[i] == '\n') buffer[i] = '\0';
    }
}


int main() {
    char buffer[BUFFER_SIZE];
    cout << "Enter lines of text (" << BUFFER_SIZE << " characters):" << endl;
    cin.read(buffer, BUFFER_SIZE);


    buffer[BUFFER_SIZE - 1] = '\0';
    replaceNewLineChars(buffer);


    char* lines[LAST_LINES_SIZE];
    int linesCount = findLastLines(buffer, lines);


    cout << "Last " << LAST_LINES_SIZE << " lines in reverse order:" << endl;


    for (int i = 0; i < linesCount; i++) {
        cout << lines[i] << endl;
    }


    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

Adnan
18.12.21, 14:07

Really amazing...Thank you for solving my problem

Leave a comment

LATEST TUTORIALS
New on Blog