473,387 Members | 1,687 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

C++ Primer ex 4.30

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 $
--
-- http://arnuld.blogspot.com

Jul 24 '07 #1
9 1465
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
Jul 24 '07 #2
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
I think you needn't place a space here (just like the function `strcat')
terminator in the end, so we added 2 here */

char* final_sl = new char[final_size];

strcpy(final_sl, sl1);
strcat(final_sl, " ");
I think you cannot use `strcat' here, because you are now implementing
another `strcat'.
/* 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 $

Jul 24 '07 #3
In article <pa****************************@gmail.com>,
ge*********@gmail.com says...

[ ... ]
* 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.
Just FWIW, I don't see anything here to indicate that you're supposed to
put a space between the strings being concatenated.

[ ... ]
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);
I think I'd replace this chunk of code with something like:

sprintf(final_s1, "%s %s", sl1, sl2);

Though, of course, I doubt I'd do anything like that in C++ at all...

To answer your question, the first strcpy copies the original string
into the destination, including the terminating NUL. strcat then finds
the end of the string and overwrites the NUL with the first character in
the string being concatenated, and adds another NUL at the end of the
string it concatenates to the first. In your case, you do another
strcat, which does the same thing again. Over time, your result string
looks like:

strcpy: ['f','i','r','s','t','\0']
strcat 1: ['f','i','r','s','t',' ','\0']
strcat 2: ['f','i','r','s','t',' ','s','e','c','o','n','d','\0']

In the first two cases, the remainder of the allocated space is filled
with indeterminate data.

To answer a point you made in a related thread, both 0 and '\0' are
required to have the value zero. The only difference between them is the
type -- 0 is an int whereas '\0' is a char (unlike in C, where they both
have type int). A C-style string is terminated by a char with the value
zero.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 24 '07 #4
On Jul 24, 3:18 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:

[...]
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),
Or unless you want other people to be able to read and maintain
your code. C++ declaration syntax is already bad enough without
abusing it.
so I'd write
std::string s1("first"), s2("second"), s3(s1 + " " + s2);
So that the first professional who comes along, and is concerned
with maintainability, would have to rewrite it. That's a very
good example of something you should not do.

--
James Kanze (Gabi Software) email: ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jul 24 '07 #5
James Kanze wrote:
On Jul 24, 3:18 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:

[...]
> 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),

Or unless you want other people to be able to read and maintain
your code. C++ declaration syntax is already bad enough without
abusing it.
>so I'd write
> std::string s1("first"), s2("second"), s3(s1 + " " + s2);

So that the first professional who comes along, and is concerned
with maintainability, would have to rewrite it. That's a very
good example of something you should not do.
I just love how easy it is to get into a religious war over a non-
issue like that.
Jul 24 '07 #6
Alf P. Steinbach wrote:
* Victor Bazarov:
>James Kanze wrote:
>>On Jul 24, 3:18 pm, "Victor Bazarov" <v.Abaza...@comAcast.net>
wrote: [...]
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),
Or unless you want other people to be able to read and maintain
your code. C++ declaration syntax is already bad enough without
abusing it.

so I'd write
std::string s1("first"), s2("second"), s3(s1 + " " + s2);
So that the first professional who comes along, and is concerned
with maintainability, would have to rewrite it. That's a very
good example of something you should not do.

I just love how easy it is to get into a religious war over a non-
issue like that.

Heya Victor, I think James' follow up was quite reasonable; you was
the one using loaded words like "stupid". And I agree with James. Not
only is the source code more readable with separate declarations,
<shrug>

IMNSHO muliplying 'std::string' like it does in the code fragment above
is NOT more readable, whatever you and James may have to say about it;
everybody's standards of readability are different.

There has to be a significant number of people agreeing with some
point of view to make that point of view reasonable. As to loadedness
of any words you choose to pick on, I've dealt with enough coding
standards to have my opinion on them and to be able to call some of
them stupid. I am not going to continue this.
it's also a convention that helps avoid some simple errors, it better
supports editing, and it better supports debugging because you can
run up to a given declaration, so it's not religious, just what's
practical in C++.
It's a *style* issue. Of course it *is* religious.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 24 '07 #7
"Victor Bazarov" <v.********@comAcast.netwrote in message
news:f8**********@news.datemas.de...
Alf P. Steinbach wrote:
>* Victor Bazarov:
>>James Kanze wrote:
On Jul 24, 3:18 pm, "Victor Bazarov" <v.Abaza...@comAcast.net>
wrote: [...]
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),
Or unless you want other people to be able to read and maintain
your code. C++ declaration syntax is already bad enough without
abusing it.

so I'd write
std::string s1("first"), s2("second"), s3(s1 + " " + s2);
So that the first professional who comes along, and is concerned
with maintainability, would have to rewrite it. That's a very
good example of something you should not do.

I just love how easy it is to get into a religious war over a non-
issue like that.

Heya Victor, I think James' follow up was quite reasonable; you was
the one using loaded words like "stupid". And I agree with James. Not
only is the source code more readable with separate declarations,

<shrug>

IMNSHO muliplying 'std::string' like it does in the code fragment above
is NOT more readable, whatever you and James may have to say about it;
everybody's standards of readability are different.

There has to be a significant number of people agreeing with some
point of view to make that point of view reasonable. As to loadedness
of any words you choose to pick on, I've dealt with enough coding
standards to have my opinion on them and to be able to call some of
them stupid. I am not going to continue this.
>it's also a convention that helps avoid some simple errors, it better
supports editing, and it better supports debugging because you can
run up to a given declaration, so it's not religious, just what's
practical in C++.

It's a *style* issue. Of course it *is* religious.
Personally, I also break up declarations on each line. Its not as easy to
see each one, and some can cause confusion. Such as:
char* a, b, c;

Also, lines can tend to get long with initialization etc.. and it can get
confusing as to what is being declared.

I agree, however, that it is a style issue.

Calling a style issue you don't agree with as "stupid", however, does make
it a religious issue.
Jul 25 '07 #8
Jim Langston wrote:
[..]
Personally, I also break up declarations on each line. Its not as
easy to see each one, and some can cause confusion. Such as:
char* a, b, c;

Also, lines can tend to get long with initialization etc.. and it can
get confusing as to what is being declared.

I agree, however, that it is a style issue.

Calling a style issue you don't agree with as "stupid", however, does
make it a religious issue.
Please reread my post in which the word "stupid" appeared first.
Then please post an apology for misunderstanding of *what* I called
stupid.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 25 '07 #9
On Jul 24, 11:53 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
Alf P. Steinbach wrote:
* Victor Bazarov:
Heya Victor, I think James' follow up was quite reasonable; you was
the one using loaded words like "stupid". And I agree with James. Not
only is the source code more readable with separate declarations,
<shrug>
IMNSHO muliplying 'std::string' like it does in the code
fragment above is NOT more readable, whatever you and James
may have to say about it; everybody's standards of readability
are different.
Readability can be tested, and more or less objectively
measured. (Not that anyone is actually doing it, of course.)
There has to be a significant number of people agreeing with some
point of view to make that point of view reasonable.
Number of people agreeing is very orthogonal with reasonability.
As to loadedness of any words you choose to pick on, I've
dealt with enough coding standards to have my opinion on them
and to be able to call some of them stupid. I am not going to
continue this.
it's also a convention that helps avoid some simple errors, it better
supports editing, and it better supports debugging because you can
run up to a given declaration, so it's not religious, just what's
practical in C++.
It's a *style* issue. Of course it *is* religious.
It stops being a style issue when someone has to maintain the
code. For example, by changing the type of one of the
variables, without changing the others.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jul 25 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Sandman | last post by:
Could anyone give me a tip about a good primer on object oriented php programming - why I should use it, the benefits, the drawbacks, the bugs, the glory? And, should I upgrade to php5 before...
1
by: Charles L | last post by:
Does anyone know where I can find errata for Stan Lippman's 'C++ Primer 2nd Edition'? Charles Leng
1
by: hugo | last post by:
what is L&L ,people or book?
5
by: hajime | last post by:
I purchased this book: C++ Primer, 4th Edition ISBN: 0201721481 in Australia. The right side of the last three lines on page 231 are not legible. A stain shows a piece of paper was on that part...
7
by: Lycan. Mao.. | last post by:
Hello, I am a newbie in C++ and I'm in trouble in choosing books, I hope some one who can give me some tips. I'm already know C and a little about Scheme, C#, Python, Lua and so on, and now I want...
2
by: W. Watson | last post by:
Is there a primer out there on these two items? I have the Python tutorial, but would like either a Tkinter tutorial/primer to supplement it, or a primer/tutorial that addresses both. Maybe there's...
20
by: arnuld | last post by:
I get an error, can't find what is the problem: /* C++ Primer - 4/e * * Chapter 8, exercise 8.3 * STATEMENT * write a function that takes and returns an istream&. the function should read...
2
by: xianwei | last post by:
First, typedef struct pair { Node *parent; Node *child; } Pair; static Pair SeekItem(cosnt Item *pI, const Tree *pTree) { Pair look;
1
by: Kveldulv | last post by:
Hi all, here is the code: http://pastebin.com/m6e74d36b I'm stuck at highfink constructor, last line before #endif. As parameters, I have reference to one parent class and int member of another...
0
by: cincerite | last post by:
Hello , guys , I'm reading C++ Primer 3rd edition recently.I tried to download the errata of it from Stan Lippman's Home Page:http:// staff.develop.com/slip/ ,but it says:We're Sorry, we could not...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.