I need to prompt the user to input two separate 3 character strings and store them in arrays. Then I reserve order the strings and add them together using a third array.
"Write a program that will prompt the user for two strings. Your program should save these two strings in two different character arrays respectively. Create a third array which is used for merging these two arrays into one character array. The third array should contain all the characters from the first string + second string in a reverse order."
Example
string1= abc
string2= 123
array3 needs to produce cba321
PS when I "cout<<array1;" right after the "cin>>array1;" it works but when done after prompting for second string it doesn't
and when I "cout<<array1[0],array1[1],array1[2];" the first element doesn't appear.
#include <iostream>
#include <cstring>
int main()
{
// need to account for the C strings' null terminator ('\0')
constint arraySize { 4 };
constint finalSize { 7 };
std::cout << "Please enter the first 3 character string: ";
char cstr1[arraySize];
std::cin.getline(cstr1, arraySize);
std::cout << "Entered: " << cstr1 << '\n';
std::cout << "\nEnter the second 3 character string: ";
char cstr2[arraySize];
std::cin.getline(cstr2, arraySize);
std::cout << "Entered: " << cstr2 << '\n';
char cstr3[finalSize];
// copy the first string to the final string
// C11 added strcpy_s to prevent buffer overflows
strcpy_s(cstr3, 7, cstr1);
// concatenate the second string to the final string
// C11 added strcat_s to prevent buffer overflows
strcat_s(cstr3, 7, cstr2);
std::cout << "\nThe final string is: " << cstr3 << '\n';
}
Please enter the first 3 character string: abc
Entered: abc
Enter the second 3 character string: def
Entered: def
The final string is: abcdef
Manually mucking around with C strings is not recommended, it is too easy to forget about the null terminator. Use the C library.
If you have to manually concatenate the two C strings substitute lines 24-30 with:
24 25 26 27 28 29 30 31 32 33 34
for (int index { }; index < arraySize - 1; index++)
{
cstr3[index] = cstr1[index];
}
for (int index { }; index < arraySize - 1; index++)
{
cstr3[index + arraySize - 1] = cstr2[index];
}
cstr3[finalSize - 1] = '\0';
This is what is asked so I do not think i can use cstring
Write a program that will prompt the user for two strings. Your program should save these two strings in two different character arrays respectively. Create a third array which is used for merging these two arrays into one character array. The third array should contain all the characters from the first string + second string in a reverse order.
"cbafed" ie string1(reverse)string2(reverse). I used what you suggested and it seems to work for the first 2 arrays but im having trouble making array3=array1+array2 (I know you cannot just add them).