Write a program that receives two strings (C++ string) from the user, and create
ID: 3770393 • Letter: W
Question
Write a program that receives two strings (C++ string) from the user, and creates a third C style string (null-terminated character array) which is concatenation of two strings entered by the user.
DO NOT USE + operator to concatenate the two C++ strings. STEPS TO GUIDE YOU:
- Your first task will be to convert both the C++ strings to their corresponding C-style strings (HINT: c_str() and new will be used for this).
- After allocating dynamic memory to hold the two converted C-style strings, one needs to string copy the c_str() converted strings to their respective newly allocated space using strcpy() [Don’t forget required header file for this that needs to be included].
- These newly allocated space are pointers to the respective array of characters (or C-style string).
- Then, you must again use dynamic memory allocation technique using “new” operator to create the third C-style string (or character array) that will hold the concatenation of the above two strings. Decide what should be the size of this third C-style string that needs to be used in new.
- Using For-loop on the first two C-style strings, you will assign values to the third C-style string and display the contents of this final array. Illustration: C++ str1: “computer” C-style: (generated using new, c_str() and strcpy() ) c o m p u t e r C++ str2: “science” C-style: (generated using new, c_str() and strcpy() ) s c i e n c e Concatenated C-style string: c o m p u t e r s c i e n c e Print the two strings entered by the user, and the third string generated.
Eg : Strings entered by the user computer science Output : computer science computer science
Explanation / Answer
#include<iostream>
#include<conio>
#include<string>
using namespace:std
void main()
{
string s1="computer science", s2="computer science";
char s3[20];
int i,c=0;
char* cstr=new char[s1.length()+1];
strcpy(cstr,s1.c_str());
char* cstr1=new char[s2.length()+1];
strcpy(cstr1,s2.c_str());
for(i=0;i<strlen(cstr);i++)
{
s3[c]=cstr[i];
c++;
}
for(i=0;i<strlen(cstr1);i++)
{
s3[c]=cstr1[i];
c++;
}
cout<<s1<<endl<<s2<<endl<<"concatenated C-style string:"<<s3;
getch();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.