Flamur Kelmendi Flamur Kelmendi - 1 month ago 9
C++ Question

How to flip a Char array with pointers in C++

the function of my program is to simply have a char array with a first and last name, and switch it so it is last name first name.
(Tom,Cruise --> Cruise,Tom). I have just started using pointers and cannot find a way to rearrange the Char array. I have tried for-loops and while loops but I don't really know how to tackle this problem. I don't necessarily need hard code. Even a suggestion would help get me moving in the right direction. I am not getting any errors. Due to requirements I am unable to modify the main function whatsoever and the function header has to be

char *LastFirstName(char *ptr).


Thanks

#include <iostream>
using namespace std;

char *LastFirstName(char *name);

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

ptr = LastFirstName(name);
cout << "After calling function LastFirstName(), name is " << ptr << endl;

system("pause");
return 0;
}

// This is where I am havinbg trouble
char *LastFirstName(char *ptr) {
char *p;
p = ptr;
int len = strlen(ptr);

return ptr;
}

Answer

You can use this function:

void LastFirstName(char* first_last_name)
{
    char first_name[41] = {0};
    char last_name[41]  = {0};

    // Dunno what is your separator ' ' or ','...
    char* sep_index = strchr(first_last_name, ','); // This return the first index of ','.
    *sep_index = '\0';

    strcpy(first_name, first_last_name); // Lets copy first name.
    strcpy(last_name,  first_last_name + strlen(first_last_name) + 1); // Lets copy last name.

    // Lets copy it in reverse order.
    strcpy(first_last_name, last_name);
    strcpy(first_last_name + strlen(last_name) + 1, first_name);
    first_last_name[strlen(last_name)] = ',';
}

Notice that we don't need to return char* because the function is modifying the array it received as argument, so actually name array is now reversed as requested.