I am completely new to programming and I need help with my homework assingment, I have to give it in by Thursday evening. Here is the problem, I appreciate your help.
Write a program that reads lines of text and appends them to a char buffer[1000]. Read one character at a time by calling cin.get(ch), where ch is a variable of type char. Use input redirection. 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>
usingnamespace std;
int main()
{
constint BUFFER_CAPACITY = 1000;
constint LINES_CAPACITY = 100;
char buffer[BUFFER_CAPACITY];
char* lines[LINES_CAPACITY];
// Declare variables to keep track of where we
// are in the buffer and the lines array.
// The position will start numbering at zero, so
// the position should never equal the full capacity
// (should always be at least one less).
int buffer_position = 0;
int lines_position = 0;
bool more = true;
bool newline = true;
while (more)
{
// Note, the .get() function is actually introduced
// in Chapter 8, but is needed here to be able to
// read white space (spaces, tabs, newlines, etc.)
char c = cin.get();
if (cin.fail())
{
more = false;
}
elseif (buffer_position >= BUFFER_CAPACITY) // at (or above) capacity
{
more = false;
}
if (newline)
{
if (lines_position < LINES_CAPACITY)
{
lines[lines_position] = buffer + buffer_position;
lines_position++;
newline = false;
}
else { more = false; }
}
if (more)
{
if (c == '\n')
{
buffer[buffer_position] = '\0';
buffer_position++;
newline = true;
}
else
{
buffer[buffer_position] = c;
buffer_position++;
}
}
}
// Set the last position in buffer to null terminator.
// This will ensure that we have a null terminator in the
// array in case we were in the middle of reading characters
// when we reached capacity. If we have already reached
// capacity, then this command will actually overwrite
// the last character read into the buffer).
buffer[BUFFER_CAPACITY - 1] = '\0';
// Print the lines back in reverse order.
for (int i = lines_position - 1; i >= 0; i--)
{
cout << lines[i] << endl;
}
return 0;
}