Reversing order of sentences (College Assignment)

We were instructed to use a pointer array to get input for short sentences and then reverse the order of those sentences. My program works really well for the first input and it will actually display it last, but for the other inputs, I am missing a few characters from the start of the input and the sentences are in the order they were inputed not the reverse order. I am just looking for hints on where I may be wrong and a little push in the right direction. Thanks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <string>

using namespace std;
const int SIZE = 500;
char *counter;
const int n = 30;
void cat (char*, char*, bool);
int main()
{
	char *arrayMan [SIZE];
	char *pointerMan = new char [SIZE] ();
	int length = 0;
	int count = 0;
	int i;
	char temp [n];
	do
	{
		cout <<"Please enter a short sentence or press 0 to quit:" << endl;
		cin.getline(temp, n);
		cat(pointerMan, temp, count != 0);
		arrayMan[count++] = &pointerMan[length];// I think I have pointed out the problem to be here.
		length= strlen(temp);
	}while(*temp != '0');
	
	for (int i = count-1; i >= 0; i--)
	{
      cout << arrayMan[i] << endl;
	}
	system("PAUSE");
	return 0;
}
void cat(char* string1, char* string2, bool p)
{
	
	char* s1 = string1;
	char* s2 = string2;
	// find end of first string
	while (*string1 != '\0')
		string1++;
	if (p)
		string1++;
	// move characters of second string to the end of the first
	while (*string2 != '\0')
		*string1++ = *string2++;
	// null terminate the string
	*string1 = '\0';	
}

any help here?
There are quite a few problems with your code, but only 2 main ones. I'm

1. pointerMan is not initialised and you try to access it in function cat() on first iteration to look for '\0' even though the storage slot is empty...
2. Stuff is far too complicated for this task.
3. I think you mean sentence, rather than sentences.
4. Condition *tmp != '\0' needs to be at line 21, when the user enters 0. You're needleslly calling cat.

I don't understand line 23 and 22. You're trying to save multiple sentences into arrayMan? Don't use &, just correct line 22 to arrayMan[count++] = pointerMan;. Fix cat first, and simplify it by renaming it to reverse.

Scrap everything. Read this pseudo code and start from there.

Edit: sorry, misread your code. I'm not used to seeing global variables and static allocation.


char **sentences = alloc
loop
    readline
    exit if input = 0
    data = reverse(input)
    print data
    sentences[n++] = data /* delete this later on */
end loop

reverse (string)
    create temp [char *]
    temp += strlen(string)
    *temp = '\0'

    while (*string)
        *temp-- = *string++;

    return temp
end

Last edited on
Topic archived. No new replies allowed.