Names - Reverse order - pointers

Hello : ) I have a problem with my C++ program. I don't know how to print first and the last name in reverse order using pointers. For example if user type: "First Last" program should output: "Last, First" (with comma). I can't change a main program, use vectors or change function prototype. I also have to use dinamic allocation memory. Thank you for any help!

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
#include <iostream>
#include <iomanip>
using namespace std;

char *LastFirstName(char *name);

int main()
{
	char fullname[41], *ptr;
	// Force user to enter full name, if not entered, ask again
	while (true)
	{
		fullname[0] = '\0';
		cout << "Enter your full name: ";
		cin.getline(fullname, 40);
		if (fullname[0] == '\0')
			cout << "Name not entered. Re-enter full name.\n";
		else
			break;
	}
	cout << "Before calling function LastFirstName(), name is " << fullname << endl;
	ptr = LastFirstName(fullname);
	cout << "After calling function LastFirstName(), name is " << ptr << endl;
	system("pause"); 
	return 0;
}

// 
char *LastFirstName(char* name)
{
	int i = 41;
	char* ptr = new char(41);

	// ??? 
	for (i; i < 0;i--)
	{
		*name = ptr[i];
	}

	return ptr;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
char	*LastFirstName(char name[])
{
  int	qcs=strlen(name);
  char *lfn=(char*)malloc(qcs+2);
  int	ncsp;
  int	jcs,jct;

  for(ncsp=0;ncsp<qcs;ncsp++)
  {
    if(name[ncsp]==' ')
      break;
  }
  for(jct=0,jcs=ncsp+1;jcs<qcs;jcs++)
    lfn[jct++]=name[jcs];
  lfn[jct++]=',';
  lfn[jct++]=' ';
  for(jcs=0;jcs<ncsp;jcs++)
    lfn[jct++]=name[jcs];

  return lfn;
}
Thank you very much for your help skaa ! I know how it works now.
Topic archived. No new replies allowed.