A
arnuld
i think this needs some improvement.
/* C++ Primer - 4/e
* chapter 4- Arrays & Pointers, exercise 4.30 * STATEMENT
* write a programme to concatenate the two C-style strings literals
putting the result in a C-style string. then write a programme to
concatenate 2 standard library strings.
*/
#include <iostream>
#include <string>
#include <cstring>
int main()
{
const char* sl1 = "first";
const char* sl2 = "second";
const size_t final_size = strlen(sl1) + strlen(sl2) + 2; /* since we
need a space between the two strings and a NULL
terminator in the end, so we added 2 here */
char* final_sl = new char[final_size];
strcpy(final_sl, sl1);
strcat(final_sl, " ");
/* where does the '\0' of 1st string literal will go ?
does "final_sl" look like this:
['f','i','r','s','t','\0',' ','s','e','c','o','n','d','\0']
*/
strcat(final_sl, sl2);
std::cout << final_sl << std::endl;
delete [] final_sl;
/* standard library strings */
std::string s1 = "first";
std::string s2 = "second";
std::string s3 = s1 + " " + s2;
std::cout << s3 << std::endl;
return 0;
}
======== OUTPUT ===========
~/programming/cpp $ g++ -ansi -pedantic -Wall -Wextra ex_04-30.cpp
~/programming/cpp $ ./a.out
first second
first second
~/programming/cpp $
/* C++ Primer - 4/e
* chapter 4- Arrays & Pointers, exercise 4.30 * STATEMENT
* write a programme to concatenate the two C-style strings literals
putting the result in a C-style string. then write a programme to
concatenate 2 standard library strings.
*/
#include <iostream>
#include <string>
#include <cstring>
int main()
{
const char* sl1 = "first";
const char* sl2 = "second";
const size_t final_size = strlen(sl1) + strlen(sl2) + 2; /* since we
need a space between the two strings and a NULL
terminator in the end, so we added 2 here */
char* final_sl = new char[final_size];
strcpy(final_sl, sl1);
strcat(final_sl, " ");
/* where does the '\0' of 1st string literal will go ?
does "final_sl" look like this:
['f','i','r','s','t','\0',' ','s','e','c','o','n','d','\0']
*/
strcat(final_sl, sl2);
std::cout << final_sl << std::endl;
delete [] final_sl;
/* standard library strings */
std::string s1 = "first";
std::string s2 = "second";
std::string s3 = s1 + " " + s2;
std::cout << s3 << std::endl;
return 0;
}
======== OUTPUT ===========
~/programming/cpp $ g++ -ansi -pedantic -Wall -Wextra ex_04-30.cpp
~/programming/cpp $ ./a.out
first second
first second
~/programming/cpp $