C++ Primer ex 6.20

A

arnuld

it works fine. i am posting it to know your views (please remember, i am
at chapter 6, so i have not encountered stuf like Functions):

/* C++ Primer - 4/e
*
* exercise 6.20
* STATEMENT
* write a programme to rad a sequence of strings from standard
input until either the same word occurs twice in succession or all the
words have been read. use the while loop to read a word at a time. use
the break statement to terminate the loop if awords occurs twice in
succession & print that word or else print the message that no word was
repeated.
*
*/


#include <iostream>
#include <string>

int main()
{
std::string cstr, pstr;
bool same_str = false;

while(std::cin >> cstr)
{
if(cstr == pstr)
{
same_str = true;
break;
}

pstr = cstr;
}


if(same_str)
{
std::cout << "\n'"
<< cstr
<< "' was repeated\n";
}
else
{
std::cout << "\nno word was repeated\n";
}

return 0;
}
 
B

Barry

arnuld said:
it works fine. i am posting it to know your views (please remember, i am
at chapter 6, so i have not encountered stuf like Functions):

So, what's the point?
 
J

Jim Langston

arnuld said:
it works fine. i am posting it to know your views (please remember, i am
at chapter 6, so i have not encountered stuf like Functions):

/* C++ Primer - 4/e
*
* exercise 6.20
* STATEMENT
* write a programme to rad a sequence of strings from standard
input until either the same word occurs twice in succession or all the
words have been read. use the while loop to read a word at a time. use
the break statement to terminate the loop if awords occurs twice in
succession & print that word or else print the message that no word was
repeated.
*
*/

Personally, I'm not in favor of the break statement when other methods can
be easily used. I would rather do (untested code)
#include <iostream>
#include <string>

int main()
{
std::string cstr, pstr;
bool same_str = false;
while(! same_str && std::cin >> cstr)
 
I

int2str

thanks, i will use it :)

-- arnuldhttp://arnuld.blogspot.com

I'm not a fan of unnecessary state variables (same_str) which can be
handled by logic in the code instead.

You can also omit the "return 0;" in C++.

So I propose the following version of your code:

#include <iostream>
#include <string>

int main()
{
std::string cstr, pstr;

while( std::cin >> cstr && pstr != cstr )
{
pstr = cstr;
cstr = "";
}

if( cstr != "" )
std::cout << "\n'" << cstr << "' was repeated\n";
else
std::cout << "\nno word was repeated\n";
}

Cheers,
Andre
 
V

Victor Bazarov

BobR said:
BUT, why would you want to?

Lazy?

<shrug> I don't understand the desire to label somebody right away
with a negative epithet. Every use of a member name in a non-static
member function _can_ be preceded by 'this->'. Do *you* do that?
I don't think so. Why? Lazy? It's unnecessary in *most* cases.

Same here. It's unnecessary to spell out "return 0;". What do you
*gain* (except more typing exercise for your hands) when you spell
it out?

V
 
W

werasm

Jim said:
Personally, I'm not in favor of the break statement when other methods can
be easily used. I would rather do (untested code)
[snip]

while(! same_str && std::cin >> cstr)
{
if(cstr == pstr)
same_str = true;
pstr = cstr;
}


This causes one unnecessary string assignment, even
though the strings already tested equal. IMO this could
be regarded as pessimizing prematurely (for the sake
of not using a break?). It also causes additional an
comparison. If you did not want to break, the least
you could have done is continue after the if( cstr == pstr ).
Matter of style: Using no braces after if is often a source
of error.
 
J

James Kanze

I'm not a fan of unnecessary state variables (same_str) which can be
handled by logic in the code instead.
You can also omit the "return 0;" in C++.

You can, but not everything that you can do you should do. The
return is good form, and I would generally criticize a
programmer for omitting it.
 
W

werasm

arnuld wrote:

int main()
{
std::string cstr, pstr;
bool same_str = false;

while(std::cin >> cstr)
{
if(cstr == pstr)
{
same_str = true;
break;
}

pstr = cstr;
}


if(same_str)
{
std::cout << "\n'"
<< cstr
<< "' was repeated\n";
}
else
{
std::cout << "\nno word was repeated\n";
}

return 0;
}

As I see it, if the end of std::cin is reach (highly unlikely but
possible
if you associate it with a file buffer, for instance), then the
duplicate
consecutive words were not found (due to your break). For this reason
the boolean same_str is unnecessary, and only serves a documenting
purpose.

This could have been a possible solution:

int main()
{
using namespace std;

string prev, next;
while( cin >> next )
{
if( prev != next )
{
prev = next;
continue;
}
break;
}

if( cin.eof() == false ) //...or if( !cin.eof() ) if you like
{
cout << "Word repeated was " << next;
}
else
{
cout << "No word repeated";
}
cout << "." << endl;
}
 
B

BobR

Victor Bazarov said:
<shrug> I don't understand the desire to label somebody right away
with a negative epithet.

Not epithetical, just a question.
Every use of a member name in a non-static
member function _can_ be preceded by 'this->'. Do *you* do that?

Sometimes, yes.
I don't think so. Why? Lazy? It's unnecessary in *most* cases.

And in other cases, it makes it clear enough that you don't need to write a
long comment on it.
Same here. It's unnecessary to spell out "return 0;". What do you
*gain* (except more typing exercise for your hands) when you spell
it out?

So, we should put this line in the FAQ:

"DO NOT write 'return 0;' in main()"!

<G>

It seems silly to tell a newbie not to do it.
And what about old code in books/net (often posted by newbies):

void main(){
return 0;
}

Now the compiler *should* complain!
(assume an old compiler that didn't flag the 'void'.)
 
B

BobR

Jim Langston said:
Personally, I'm not in favor of the break statement when other methods can
be easily used. I would rather do (untested code)

Unfortunately, the 'break' *is in* the spec.
/*
while(! same_str && std::cin >> cstr){
*/
while( ! same_str && std::cin >> cstr ){
same_str = ( cstr == pstr );
pstr = cstr;
// if( same_str ){ cstr += "break;"; } // for spec :-}
}
 
J

Jim Langston

werasm said:
Jim said:
Personally, I'm not in favor of the break statement when other methods
can
be easily used. I would rather do (untested code)
[snip]

while(! same_str && std::cin >> cstr)
{
if(cstr == pstr)
same_str = true;
pstr = cstr;
}


This causes one unnecessary string assignment, even
though the strings already tested equal. IMO this could
be regarded as pessimizing prematurely (for the sake
of not using a break?). It also causes additional an
comparison. If you did not want to break, the least
you could have done is continue after the if( cstr == pstr ).
Matter of style: Using no braces after if is often a source
of error.

RE: the matter of style. I've gone back and forth on this over the years.
I've done it so I always use brackets. I've done it so I don't use brackets
unless I have to. I've done it where I'd use brackets if it was a function
call, etc...

At this point in time I'm not using brackets when not needed and in my own
code it hasn't caused any problems of any importance (something that took me
more than a minute or two to find and fix). But then, I've read many many
lines of code in many many languages over the years in many formats.

I tend to go for the white space format, I.E.

if ( condition )
{
statements
}

rather than

if ( condition ) {
statements
}

Which may make a difference. It would be easy to miss the fact that there
is only one statement if you are not used to seeing a bracket on the
preceeding line.
 
J

James Kanze

<shrug> I don't understand the desire to label somebody right away
with a negative epithet.

There's a question mark. He's not labeling anybody. He's
asking if that is the reason (which is, IMHO, an indirect way to
ask whether there are any other reasons).
Every use of a member name in a non-static
member function _can_ be preceded by 'this->'. Do *you* do that?
I don't think so. Why? Lazy? It's unnecessary in *most* cases.

Coherence. I never use this->. I always put a return at the
end of a function which has a return value. Why should main be
an exception.

In practice, of course, I don't think I've ever written any real
code where it was just "return 0". Any real program will have
output somewhere, output can fail, and if the output fails, you
don't want to return 0. You might as well get into the habit of
writing the return, since it's going to be necessary in any
program that is actually used.
Same here. It's unnecessary to spell out "return 0;". What do you
*gain* (except more typing exercise for your hands) when you spell
it out?

Coherence. Orthogonality.
 
J

James Kanze

[Totally changing topic, but...]
I tend to go for the white space format, I.E.
if ( condition )
{
statements

}
rather than
if ( condition ) {
statements

}

You put a blank line before the closing brace. I've noticed
this a lot recently (in the past year or two?), but had never
seen it (or at least noticed it) before, and I don't do it
myself.

I'm curious as to why? Is it an intentional decision, or is it
based on some tool, or what?
Which may make a difference. It would be easy to miss the
fact that there is only one statement if you are not used to
seeing a bracket on the preceeding line.

Agreed. Like you, I've used different styles over time. The
important thing is that the code has an "expected" look; if you
change something, and that look isn't there, it strikes you
immediately. If the rule is "a flow control statement is
followed either by a single indented statement, or a { on a line
by itself, not indented", then adding a second statement just
doesn't look right unless you add the {.
 
W

werasm

James Kanze wrote:

Agreed. Like you, I've used different styles over time. The
important thing is that the code has an "expected" look; if you
change something, and that look isn't there, it strikes you
immediately. If the rule is "a flow control statement is
followed either by a single indented statement, or a { on a line
by itself, not indented", then adding a second statement just
doesn't look right unless you add the {.

Certain style issues don't concern me that much, such
as brace positions and naming conventions, as long as
consistency exists. Other style issues could lead to errors,
and I consider lack of braces one such.

For instance in...

if( condition )
doX();
doY();

doY() could easily be mistaken (by a quick reader) as
part of the condition, where in this case:

if( condition )
{ doX(); }
doY();

or variations therefore, the mistake is less possible.

Werner
 
R

Richard

werasm said:
James Kanze wrote:



Certain style issues don't concern me that much, such
as brace positions and naming conventions, as long as
consistency exists. Other style issues could lead to errors,
and I consider lack of braces one such.

For instance in...

if( condition )
doX();
doY();

doY() could easily be mistaken (by a quick reader) as
part of the condition, where in this case:

if( condition )
{ doX(); }
doY();

And one of the main reasons to advocate the K&R bracketing because in
your example the brackets are easily missed, especially in longer lines.

if (f){
doX();
}
doY();

leaves no room for confusion. Obviously the good tab lengths (Linux src
is 8) and indenting correctly helps eliminate any issue regardless.
or variations therefore, the mistake is less possible.

Werner

--
 
V

Victor Bazarov

Richard said:
[..] Obviously the good tab lengths (Linux
src is 8) [..]

The "tab length" is a setting of a text editor. How can "src" have
any "tab length"? Did you mean indentation offset in spaces? I,
personally, hate tab characters in the source.

V
 
A

Alf P. Steinbach

* Victor Bazarov:
Richard said:
[..] Obviously the good tab lengths (Linux
src is 8) [..]

The "tab length" is a setting of a text editor. How can "src" have
any "tab length"? Did you mean indentation offset in spaces? I,
personally, hate tab characters in the source.

Bah. As long as you just remember that 1 tab = 3 spaces, it's a boon to
productivity. I think. <g>

Seriously, 4 spaces per tab is of course the only sane choice.

Heh heh...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

C++ Primer ex 9.14 11
C++ Primer ex 3.14 8
C++ Primer ex 7.12 2
C++ Primer ex 5.18 5
C++ Primer ex 7.14 2
C++ Primer ex 8.3 21
C++ Primer ex 4.30 10
C++ Primer ex 7.3 21

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top