185k views
0 votes
In C++, create a function that reverses a string, then write a second function that concatenates two strings to the buffer combine. strncpy and strncat may be used for the second function. These two functions will then be tested in main. Only use any of the following libraries: iostream, iomanip, cmath, string, fstream, sstream, vector, cstdlib, ctime, cctype, cstring. Functions: void reverse(char s[])// reverses character string

1 Answer

3 votes

Final answer:

To solve this problem, write a function to reverse a string using a loop that swaps characters and another to concatenate two strings with strncpy and strncat.

Step-by-step explanation:

To reverse a string in C++, you can create a function that takes a character array as an argument and swaps the characters from beginning to end until the halfway point is reached. To concatenate two strings, you can use a second function that utilizes strncpy and strncat to copy and append the two strings into the buffer 'combine'.

Here is an example implementation:

void reverse(char s[]) {
int length = strlen(s);
for (int i = 0; i < length / 2; i++) {
char temp = s[i];
s[i] = s[length - 1 - i];
s[length - 1 - i] = temp;
}
}

void concatenate(char combine[], const char s1[], const char s2[]) {
strncpy(combine, s1, strlen(s1) + 1);
strncat(combine, s2, strlen(s2));
}

Then, you would test these functions in the main function. Remember, the buffer 'combine' must be large enough to hold both strings and the null terminator.

User Reckoner
by
7.7k points