Re: C++ Primer ex 4.30
arnuld wrote:
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 ?
Nowhere. It stays in the 1st literal. The destination string gets
its own temrinator after each 'strcpy' or 'strcat', but every time
you invoke 'strcat' again, the terminator is overridden by the first
character of the source string.
does "final_sl" look like this:
['f','i','r','s','t','\0',' ','s','e','c','o','n','d','\0']
No, it does not. Drop the first null char, then you get the real
string. Examine the contents in the debugger or print it out char
by char (since it's an array, after all) in a loop. You will see
that there is no first '\0'. BTW, if there were, the output would
consist only of "first" and no " second" because it would stop at
the null character.
*/
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;
I prefer direct initialisation:
std::string s1("first");
std::string s2("second");
std::string s3(s1 + " " + s2);
And really there is no sense to have three separate statements
to declare/define those objects (unless your company's stupid
coding standard requires those), so I'd write
std::string s1("first"), s2("second"), 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 $
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask