473,396 Members | 1,907 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,396 software developers and data experts.

any improvements for this programme

/* C++ Primer 4/e
* section 3.2 - String Standard Library

* exercise 3.8
* STATEMENT
* write a programme to read strings from standard input, concatenate
all of them * in one string where each input string is seperated by
whitespace and then print it. */

#include <iostream>
#include <string>

int main()
{
std::string input_string, final_string;

while(std::cin >input_string)
if(final_string.empty()) // without "if" we will get a
whitespace
final_string += input_string; // at the beginning of final_string.
else
final_string = final_string + " " + input_string;

std::cout << final_string << std::endl;

return 0;
}
it works fine
-- http://arnuld.blogspot.com
Jul 18 '07 #1
16 1381
arnuld wrote:
/* C++ Primer 4/e
* section 3.2 - String Standard Library

* exercise 3.8
* STATEMENT
* write a programme to read strings from standard input, concatenate
all of them * in one string where each input string is seperated by
whitespace and then print it. */

#include <iostream>
#include <string>

int main()
{
std::string input_string, final_string;

while(std::cin >input_string)
if(final_string.empty()) // without "if" we will get a
whitespace
final_string += input_string; // at the beginning of final_string.
else
final_string = final_string + " " + input_string;

std::cout << final_string << std::endl;

return 0;
}
Put your expressions in braces, it makes the code clearer and easier to
maintain.

Try and avoid posting code with end of line comments that wrap, C style
comments are safer for Usenet.

--
Ian Collins.
Jul 18 '07 #2
On Wed, 18 Jul 2007 20:44:31 +1200, Ian Collins wrote:
Put your expressions in braces, it makes the code clearer and easier to
maintain.
ok.. done
Try and avoid posting code with end of line comments that wrap,
i donot get it. what are "end of line comments that wrap" ?
C style comments are safer for Usenet.
ok you said /* */ are safer for USENET but not for C++ programmer ??

--
-- http://arnuld.blogspot.com

Jul 18 '07 #3
arnuld wrote:
>On Wed, 18 Jul 2007 20:44:31 +1200, Ian Collins wrote:
>Put your expressions in braces, it makes the code clearer and easier to
maintain.

ok.. done
>Try and avoid posting code with end of line comments that wrap,

i donot get it. what are "end of line comments that wrap" ?
Look at how your code appeared after you posted it, your comment after
the if wrapped to the next line, so if anyone tried to copy and past the
code to compile it, they would have to fix up the code first.
>C style comments are safer for Usenet.

ok you said /* */ are safer for USENET but not for C++ programmer ??
if(final_string.empty()) // without "if" we will get a
whitespace

won't compile

if(final_string.empty()) /* without "if" we will get a
whitespace */

will.

--
Ian Collins.
Jul 18 '07 #4
"arnuld" <ge*********@gmail.comwrote in message
news:pa****************************@gmail.com...
/* C++ Primer 4/e
* section 3.2 - String Standard Library

* exercise 3.8
* STATEMENT
* write a programme to read strings from standard input, concatenate
all of them * in one string where each input string is seperated by
whitespace and then print it. */

#include <iostream>
#include <string>

int main()
{
std::string input_string, final_string;

while(std::cin >input_string)
if(final_string.empty()) // without "if" we will get a
whitespace
final_string += input_string; // at the beginning of final_string.
At this point final_string is empty. += is rather unneeded, although it
would work. I would rather change this line to:
final_string = input_string;

Does the exact same thing in the end, but makes it clearer what is going on.
else
final_string = final_string + " " + input_string;

std::cout << final_string << std::endl;

return 0;
}
it works fine
-- http://arnuld.blogspot.com

Jul 18 '07 #5
On 2007-07-18 10:28, arnuld wrote:
/* C++ Primer 4/e
* section 3.2 - String Standard Library

* exercise 3.8
* STATEMENT
* write a programme to read strings from standard input, concatenate
all of them * in one string where each input string is seperated by
whitespace and then print it. */

#include <iostream>
#include <string>

int main()
{
std::string input_string, final_string;

while(std::cin >input_string)
To me a string can contain white-spaces, this code reads words and
concatenates them. The question is a bit vague on this issue but I'd use
getline() and use the definition string == line. Just a thought.

--
Erik Wikström
Jul 18 '07 #6
On Wed, 18 Jul 2007 20:44:31 +1200, Ian Collins wrote:
arnuld wrote:
>/* C++ Primer 4/e
* section 3.2 - String Standard Library

* exercise 3.8
* STATEMENT
* write a programme to read strings from standard input,
concatenate all of them * in one string where each input string is
seperated by whitespace and then print it. */

#include <iostream>
#include <string>

int main()
{
std::string input_string, final_string;

while(std::cin >input_string)
if(final_string.empty()) // without "if" we will get a
whitespace
final_string += input_string; // at the beginning of
final_string.
else
final_string = final_string + " " + input_string;

std::cout << final_string << std::endl;

return 0;
}
Put your expressions in braces, it makes the code clearer and easier to
maintain.
That is in no way a generally accepted opinion. I find the code more
readable without the braces.

--
Markus Schoder
Jul 18 '07 #7
In article <pa****************************@gmail.com>,
ge*********@gmail.com says...
/* C++ Primer 4/e
* section 3.2 - String Standard Library

* exercise 3.8
* STATEMENT
* write a programme to read strings from standard input, concatenate
all of them * in one string where each input string is seperated by
whitespace and then print it. */

#include <iostream>
#include <string>

int main()
{
std::string input_string, final_string;

while(std::cin >input_string)
if(final_string.empty()) // without "if" we will get a
whitespace
final_string += input_string; // at the beginning of final_string.
else
final_string = final_string + " " + input_string;

std::cout << final_string << std::endl;

return 0;
}
I'd generally do things a bit differently. Right now, you have a (mildly
messy) if statement in the inner loop. Unless it's crucial that there
NOT be an extra space after the final string, I'd just add a space after
the end of each string, which would simplify the code considerably.

Unless you're going to do something else with the data while it's stored
as a big string, I'd avoid using up the storage, and just copy data from
input to output, with padding added as necessary.

I'd consider using a standard algorithm instead of an explicit loop. The
first simplification (often) makes this step easier since it allows all
input to be treated uniformly.

Putting all those together gives a program that's quite a bit simpler,
but gives similar results:

#include <iostream>
#include <iterator>
#include <algorithm>

int main() {
std::copy(std::istream_iterator<std::string>(std:: cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, " "));
return 0;
}

To meet the original specification, we can use a stringstream instead of
copying directly to cout, and remove the extra space from the
intermediate string:

int main() {
std::ostringstream temp;

std::copy(std::istream_iterator<std::string>(std:: cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(temp, " "));

std::string data = std::string(temp.str(),
0,
temp.str().length()-1);

std::cout << data;

return 0;
}

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 21 '07 #8
On Sat, 21 Jul 2007 08:23:42 -0600, Jerry Coffin wrote:
I'd generally do things a bit differently. Right now, you have a (mildly
messy) if statement in the inner loop. Unless it's crucial that there
NOT be an extra space after the final string, I'd just add a space after
the end of each string, which would simplify the code considerably.
yes, you are right but someone mentioned it on the newsgroup, IIRC.
#include <iostream>
#include <iterator>
#include <algorithm>

int main() {
std::copy(std::istream_iterator<std::string>(std:: cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, " "));
return 0;
}
this code runs but it prints everything as sson as i press "Enter". i
think the problem wants us to print the input only when EOF is
encountered.
int main() {
std::ostringstream temp;

std::copy(std::istream_iterator<std::string>(std:: cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(temp, " "));

std::string data = std::string(temp.str(),
0,
temp.str().length()-1);

std::cout << data;

return 0;
}
this gives error at line: "std::ostringstream temp;"

{arnuld@arch cpp }% g++ -ansi -pedantic -Wall -Wextra RL_3.8.cpp
RL_3.8.cpp: In function ‘int main()’:
RL_3.8.cpp:26: error: aggregate ‘std::ostringstream temp’ has incomplete type and cannot be defined
RL_3.8.cpp:32: error: ‘length’ was not declared in this scope
RL_3.8.cpp:32: error: expected primary-expression before ‘(’ token
RL_3.8.cpp:32: error: expected unqualified-id before ‘(’ token
{arnuld@arch cpp }%
-- http://arnuld.blogspot.com
Jul 22 '07 #9

arnuld <ge*********@gmail.comwrote in message...
On Sat, 21 Jul 2007 08:23:42 -0600, Jerry Coffin wrote:
int main() {
std::ostringstream temp;

std::copy(std::istream_iterator<std::string>(std:: cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(temp, " "));

std::string data = std::string(temp.str(),
0,
temp.str().length()-1);

std::cout << data;
return 0;
}

this gives error at line: "std::ostringstream temp;"
#include <sstream// plus the other headers

--
Bob R
POVrookie
Jul 22 '07 #10
On Jul 18, 11:04 am, arnuld <geek.arn...@gmail.comwrote:
On Wed, 18 Jul 2007 20:44:31 +1200, Ian Collins wrote:
Try and avoid posting code with end of line comments that wrap,
i donot get it. what are "end of line comments that wrap" ?
Some newreaders wrap lines that are too long, which results in
the end of the comment showing up on a new line (without a
leading //).

The easiest way to avoid this is to limit your line length; I
think 64 characters is generally safe.

An even easier way is to suppose that people are intelligent
enough to recognize the problem, and fix it. Whether this is an
appropriate solution depends on the purpose of your posting is:
if it is sample code that we should copy/paste into an editor,
then compile, then it's not a good idea; if the goal is just to
illustrate a point, so that something can be better understood,
it's usually OK.
C style comments are safer for Usenet.
ok you said /* */ are safer for USENET but not for C++ programmer ??
There's nothing "unsafe" about C style comments. They're just a
pain to maintain in project code.

--
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 22 '07 #11
On Jul 21, 4:23 pm, Jerry Coffin <jcof...@taeus.comwrote:
In article <pan.2007.07.18.08.28.23.597...@gmail.com>,
geek.arn...@gmail.com says...
/* C++ Primer 4/e
* section 3.2 - String Standard Library
* exercise 3.8
* STATEMENT
* write a programme to read strings from standard input, concatenate
all of them * in one string where each input string is seperated by
whitespace and then print it. */
#include <iostream>
#include <string>
int main()
{
std::string input_string, final_string;
while(std::cin >input_string)
if(final_string.empty()) // without "if" we will get a
whitespace
final_string += input_string; // at the beginning of final_string.
else
final_string = final_string + " " + input_string;
std::cout << final_string << std::endl;
return 0;
}
I'd generally do things a bit differently. Right now, you have a (mildly
messy) if statement in the inner loop. Unless it's crucial that there
NOT be an extra space after the final string, I'd just add a space after
the end of each string, which would simplify the code considerably.
In this case, you're probably right. For this specific case, I
would also consider:

while ( std::cin >input_string ) {
final_string += ' ' ;
final_string += input_string ;
}
std::cout << final_string.substr( 1 ) << std::endl ;

or:

while ( std::cin >input_string ) {
if ( ! final_string.empty() ) {
final_string += ' ' ;
}
final_string += input_string ;
}

More generally, however, I use something like:

int inLineCount = 0 ;
while ( whatever ) {
if ( inLineCount == 0 ) {
output line header...
} else {
output separator...
}
output value
++ inLineCount ;
if ( inLineCount >= maxInLine ) {
output end of line...
inLineCount = 0 ;
}
}

It's a standard pattern, which covers a lot of cases. In
practice, I find it more effort to eliminate the if's in the
special cases than to just use a standard pattern everywhere.

--
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 22 '07 #12
In article <pa****************************@gmail.com>,
ge*********@gmail.com says...
On Sat, 21 Jul 2007 08:23:42 -0600, Jerry Coffin wrote:
I'd generally do things a bit differently. Right now, you have a (mildly
messy) if statement in the inner loop. Unless it's crucial that there
NOT be an extra space after the final string, I'd just add a space after
the end of each string, which would simplify the code considerably.

yes, you are right but someone mentioned it on the newsgroup, IIRC.
I didn't see it, but I may (easily) have missed a post...
#include <iostream>
#include <iterator>
#include <algorithm>

int main() {
std::copy(std::istream_iterator<std::string>(std:: cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, " "));
return 0;
}

this code runs but it prints everything as sson as i press "Enter". i
think the problem wants us to print the input only when EOF is
encountered.
Yes -- rather than storing the data, it simply processes data and
produces output immediately.
int main() {
std::ostringstream temp;

std::copy(std::istream_iterator<std::string>(std:: cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(temp, " "));

std::string data = std::string(temp.str(),
0,
temp.str().length()-1);

std::cout << data;

return 0;
}

this gives error at line: "std::ostringstream temp;"
Try adding:

#include <sstream>

up toward the beginning of the file and see if it doesn't help.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 22 '07 #13
On Sun, 22 Jul 2007 13:55:20 -0600, Jerry Coffin wrote:
>ge*********@gmail.com says...
yes, you are right but someone mentioned it on the newsgroup, IIRC.
I didn't see it, but I may (easily) have missed a post...
yes, it is not there and nobosy mentioned it. i think that may be a
thought that came to mind while writing the programme 1st time :-)
> ...[SNIPPED]........
std::copy(std::istream_iterator<std::string>(std:: cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(temp, " "));

std::string data = std::string(temp.str(),
0,
temp.str().length()-1);

std::cout << data;

return 0;
}
}
>this gives error at line: "std::ostringstream temp;"
Try adding: #include <sstream>
up toward the beginning of the file and see if it doesn't help.
yes it works. dinot know that "ostream_iterator" is defined in "<sstream>"
header. BTW, it eats all newlines in the end of input, so i added a
"std::cout << std::endl" just before "return 0", so that the output
doesnot came on the same line as my hostnam eon terminal :-)

-- http://arnuld.blogspot.com

Jul 23 '07 #14
On Jul 23, 6:15 pm, arnuld <geek.arn...@gmail.comwrote:
On Sun, 22 Jul 2007 13:55:20 -0600, Jerry Coffin wrote:
geek.arn...@gmail.com says...
...[SNIPPED]........
std::copy(std::istream_iterator<std::string>(std:: cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(temp, " "));
std::string data = std::string(temp.str(),
0,
temp.str().length()-1);
std::cout << data;
return 0;
}
}
this gives error at line: "std::ostringstream temp;"
Try adding: #include <sstream>
up toward the beginning of the file and see if it doesn't help.
yes it works. dinot know that "ostream_iterator" is defined in
"<sstream>" header.
The <sstreamheader is for the ostringstream. ostream_iterator
is defined in <iterator>. (But any standard header is allowed
to include any other, and <iteratoris likely included in a
header you've already included.)
BTW, it eats all newlines in the end of input, so i added a
"std::cout << std::endl" just before "return 0", so that the output
doesnot came on the same line as my hostnam eon terminal :-)
You mean that it doesn't generate a final newline on output.
Jerry just forgot that, I suppose. (I've seen shells which
always output an extra newline before the prompt, just to avoid
this problem. The problem then is that you have an extra emptly
line everytime you run a program which works correctly.)

--
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 #15
In article <pa****************************@gmail.com>,
ge*********@gmail.com says...

[ ... ]
yes it works. dinot know that "ostream_iterator" is defined in "<sstream>"
header.
It's not -- the iterator types are declared in <itertor>.
BTW, it eats all newlines in the end of input, so i added a
"std::cout << std::endl" just before "return 0", so that the output
doesnot came on the same line as my hostnam eon terminal :-)
Yup -- I left out that detail. As an aside, I'd note that std::newline
flushes the output stream along with adding a newline character. Unless
you really need this behavior, simply writing out a "\n" accomplishes
the same thing, generally more efficiently. In this case, you're doing
it immediately before the stream is destroyed, which flushes the stream
in any case, so you're flushing the stream twice for no particularly
good reason. One extra flush rarely means much, but it's something to
keep in mind if (for example) you're writing out a large amount of data
in a loop -- in such a situation, flushing after every line can make the
program considerably slower.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 24 '07 #16
On Jul 24, 6:21 pm, Jerry Coffin <jcof...@taeus.comwrote:
In article <pan.2007.07.23.16.15.44.637...@gmail.com>,
geek.arn...@gmail.com says...
[ ... ]
Yup -- I left out that detail. As an aside, I'd note that std::newline
flushes the output stream along with adding a newline character. Unless
you really need this behavior, simply writing out a "\n" accomplishes
the same thing, generally more efficiently.
You're an experienced programmer. You automatically know when
you need to flush, without thinking about it, and your programs
probably don't core dump zillions of times before you finally
get them running. The default is (or should be) std::endl, so
that you get the flush. So that in case of a core dump, your
output reflects (sort of) how far you've gotten.
In this case, you're doing
it immediately before the stream is destroyed, which flushes the stream
in any case, so you're flushing the stream twice for no particularly
good reason. One extra flush rarely means much, but it's something to
keep in mind if (for example) you're writing out a large amount of data
in a loop -- in such a situation, flushing after every line can make the
program considerably slower.
If the data set is large enough, yes, you may have to think
about it. I wouldn't put the use of '\n' up there with
premature optimizations. But for beginners, I still think that
std::endl is the better default. (In my professional code, it's
always std::endl. But that's because the only streaming output
is to a log file, where you definitely do want the flush.)

--
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 #17

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

Similar topics

2
by: NDAKI MBOULET | last post by:
J'ai un problème pour écrire un programme. Voici mon sujet: Ecrire en c++ un programme qui reçoit en entrée une suite d'instruction encadrées par les mots clés BIBODLE et LISUK dans un langage...
5
by: Pekka Jarvela | last post by:
I am a beginner and have written a C++ programme in Visual Studio ..NET. Now, programme is for time being Console application (= works in DOS window). I would however like that it had graphical...
23
by: Rotem | last post by:
Hi, while working on something in my current project I have made several improvements to the logging package in Python, two of them are worth mentioning: 1. addition of a logging record field...
2
by: Bennett Smith | last post by:
Could anyone within Microsoft comment on the status of the XmlResolver class in upcoming versions of the .NET framework? I am particularly interested in hearing about any improvements in how...
5
by: katekukku | last post by:
HI, I need the source code for a programme in C. It should have the basic features of a paint programme like circle, line etc, etc,. I lost a programme which wa driven by keyboard, if somebody...
4
by: Frank Potter | last post by:
I want to search something by a key word from inside my py script. The using google idea comes to my mind first because write a search programme from scratch is not so easy. I want to take...
0
by: =?Utf-8?B?SmF5ZQ==?= | last post by:
I have created the programme, then using the font in Office 2007. However the user's PC haven't install the font style, when i publish my programme by clickonce, and the user use it, the font style...
7
vikas251074
by: vikas251074 | last post by:
Can I get automatic focus on first text item just after running programme? Because when I run the programme, there is no focus on any text item at the first instant. I have to use mouse to go to...
18
by: maxhugen | last post by:
I have an Access app (split into FE and BE) running for some years, that is now also being used in a second office, connected by a WAN. This office has network problems, as it's over-utilized (97%...
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:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.