473,563 Members | 2,895 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Stroustrup 5.9 exercise 11

it works fine without any trouble. i want to have advice on improving
the code from any angle like readability, maintenance etc:

---------- PROGRAMME ------------
/* Stroustrup, 5.9, exercise 11

STATEMENT:
Read a sequence of words from the input. use "quit" as the word
to terminate the input. Print the words in the order they were
entered. don't print a word twice.modify the programme to sort the
words before printing them.

*/

#include<iostre am>
#include<string >
#include<vector >

int main()
{
std::vector<std ::stringcollect _input;

std::string input_word;
std::cin >input_word;

for(int i=0; input_word != "quit"; ++i)
{
collect_input.p ush_back(input_ word);
std::cin >input_word;
}

std::cout << "\n *** Printing WOrds ***\n";

for(unsigned int i=0; i < collect_input.s ize(); ++i)
std::cout << collect_input[i]
<< '\n';

return 0;
}

----------- OUTPUT ----------------
[arch@voodo tc++pl]$ g++ -ansi -pedantic -Wall -Wextra -O
ex_5.9-11.cpp
[arch@voodo tc++pl]$ ./a.out
like this
quitting
quite
and morq quotwe FINISHED quiT quit

*** Printing WOrds ***
like
this
quitting
quite
and
morq
quotwe
FINISHED
quiT
[arch@voodo tc++pl]$

Apr 9 '07 #1
27 2422
SORRY, i just forgot to "sort" the words:

-------- PROGRAMME --------
/* Stroustrup, 5.9, exercise 11

STATEMENT:
Read a sequence of words from the input. use "quit" as the word
to terminate the input. Print the words in the order they were
entered. don't print a word twice.modify the programme to sort the
words before printing them.

*/

#include<iostre am>
#include<string >
#include<vector >
#include<algori thm>

int main()
{
std::vector<std ::stringcollect _input;

std::string input_word;
std::cin >input_word;

for(int i=0; input_word != "quit"; ++i)
{
collect_input.p ush_back(input_ word);
std::cin >input_word;
}

std::cout << "\n *** Printing Sorted Words ***\n";

// sorting the input
sort(collect_in put.begin(), collect_input.e nd());

for(unsigned int i=0; i < collect_input.s ize(); ++i)
std::cout << collect_input[i]
<< '\n';

return 0;
}

-------- OUTPUT ----------
[arch@voodo tc++pl]$ g++ -ansi -pedantic -Wall -Wextra -O
ex_5.9-11.cpp
[arch@voodo tc++pl]$ ./a.out
like this and wahout
Quit quiT and quit

*** Printing Sorted Words ***
Quit
and
and
like
quiT
this
wahout
[arch@voodo tc++pl]$
Apr 9 '07 #2
On Apr 9, 2:07 pm, "arnuld" <geek.arn...@gm ail.comwrote:

i just did not get 2 things:

// sorting the input
sort(collect_in put.begin(), collect_input.e nd());
why "std::sort" does not work ?? (as "algorithm" is a standard
library)

-------- OUTPUT ----------
[arch@voodo tc++pl]$ g++ -ansi -pedantic -Wall -Wextra -O
ex_5.9-11.cpp
[arch@voodo tc++pl]$ ./a.out
like this and wahout
Quit quiT and quit

*** Printing Sorted Words ***
Quit
and
and
like
quiT
this
wahout
[arch@voodo tc++pl]$
why "Quit" came before "and" ?

Apr 9 '07 #3
arnuld wrote:
it works fine without any trouble. i want to have advice on improving
the code from any angle like readability, maintenance etc:
The program is very well written, I like your style. I have to be very
meticolous to find something that can be improved :)
#include<iostre am>
#include<string >
#include<vector >
It's just a matter of style, but almost anybody puts a space between
#include and the angular parenthesis, because it improves the
readability a lot.
int main()
{
std::vector<std ::stringcollect _input;

std::string input_word;
std::cin >input_word;

for(int i=0; input_word != "quit"; ++i)
{
collect_input.p ush_back(input_ word);
std::cin >input_word;
}
Here I have two little suggestions. The fist is to eliminate the
repetition of the input reading, the other is that a for cycle should
perform a test that is strictly related on the variable that is being
incremented. If you don't have to iterate in some way through a
sequence, and the test is a little bit particular, it's clearer to write
it without the for. I would prefer in this situation something like:

std::vector<std ::stringcollect _input;

while(true){
std::string input_word;
std::cin >input_word;
if(input_word == "quit")
break;
else
collect_input.p ush_back(input_ word);
}

In this program is pointless to perform such a change, but in bigger
programs is very important to understand very quickly and easily the
meaning of each piece of code.

Another note: if the performances are not a priority, it is better to
declare the variables as close as possible to the point in which they
are used. For example, the string "input_word " is not that important in
the whole program, and it's used just in the for. If I'm able to declare
it into the for, I reduce the visibility of the variable to the piece of
code in which I actually use it, and I reduce the chance of error
improving the readability.
std::cout << "\n *** Printing WOrds ***\n";

for(unsigned int i=0; i < collect_input.s ize(); ++i)
std::cout << collect_input[i]
<< '\n';
Use std::size_t instead of unsigned int when you iterate on a vector. In
the std::cout line, I'd have put all the code in one line, since there
is no readability issue in separating it. Also, pay attention with the
for without parenthesis, there is nothing bad with them, but it has to
be very obvious that there is only an instruction behind them.
Otherwise, they can generate errors quite hard to detect.
Regards,

Zeppe

Apr 9 '07 #4
On Apr 9, 2:10 pm, "arnuld" <geek.arn...@gm ail.comwrote:
On Apr 9, 2:07 pm, "arnuld" <geek.arn...@gm ail.comwrote:

i just did not get 2 things:
// sorting the input
sort(collect_in put.begin(), collect_input.e nd());

why "std::sort" does not work ?? (as "algorithm" is a standard
library)
-------- OUTPUT ----------
[arch@voodo tc++pl]$ g++ -ansi -pedantic -Wall -Wextra -O
ex_5.9-11.cpp
[arch@voodo tc++pl]$ ./a.out
like this and wahout
Quit quiT and quit
*** Printing Sorted Words ***
Quit
and
and
like
quiT
this
wahout
[arch@voodo tc++pl]$

why "Quit" came before "and" ?
Why not use "set", it is ordered and will remove duplicates too.

#include <iostream>
#include <set>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;

int main()
{
string inp;
set< string s;
cin >inp;
while( inp != "quit" )
{
s.insert( inp );
cin >inp;
}

copy( s.begin(), s.end(), ostream_iterato r< string >(cout, "\n" ) );

return 0;
}

Apr 9 '07 #5
arnuld wrote:
>On Apr 9, 2:07 pm, "arnuld" <geek.arn...@gm ail.comwrote:

i just did not get 2 things:

> // sorting the input
sort(collect_in put.begin(), collect_input.e nd());

why "std::sort" does not work ?? (as "algorithm" is a standard
library)
it does not?
>
why "Quit" came before "and" ?
because it starts with a capital letter.

Regards,

Zeppe
Apr 9 '07 #6
"arnuld" <ge*********@gm ail.comwrote:
it works fine without any trouble. i want to have advice on improving
the code from any angle like readability, maintenance etc:

---------- PROGRAMME ------------
/* Stroustrup, 5.9, exercise 11

STATEMENT:
Read a sequence of words from the input. use "quit" as the word
to terminate the input. Print the words in the order they were
entered. don't print a word twice.modify the programme to sort the
words before printing them.

*/

#include<iostre am>
#include<string >
#include<vector >

int main()
{
std::vector<std ::stringcollect _input;

std::string input_word;
std::cin >input_word;

for(int i=0; input_word != "quit"; ++i)
{
collect_input.p ush_back(input_ word);
std::cin >input_word;
}
You create the variable 'i' and increment it, but never use it for
anything. Also, you never check for input failure. I suggest something
like this instead:

std::string input_word;
while ( std::cin >input_word && input_word != "quit" )
{
collect_input.p ush_back( input_word );
}
std::cout << "\n *** Printing WOrds ***\n";

for(unsigned int i=0; i < collect_input.s ize(); ++i)
std::cout << collect_input[i]
<< '\n';
A more idiomatic way of doing the above is to use std::copy:

std::copy( collect_input.b egin(), collect_input.e nd(),
ostream_iterato r<std::string> ( cout, "\n" ) );

return 0;
}
One last thing, I think you will find that the above program will print
words twice if they are entered twice. Look up std::set.
Apr 9 '07 #7
On Apr 9, 4:38 pm, "Daniel T." <danie...@earth link.netwrote:
"arnuld" <geek.arn...@gm ail.comwrote:
You create the variable 'i' and increment it, but never use it for
anything. Also, you never check for input failure. I suggest something
like this instead:

std::string input_word;
while ( std::cin >input_word && input_word != "quit" )
{
collect_input.p ush_back( input_word );
}

that is good, i will use it. IIRC, i once read the same in K&R2:

while((c = getchar()) != EOF && i < MAXLENGTH)

just mentioned it as it came to my mind

std::cout << "\n *** Printing WOrds ***\n";
for(unsigned int i=0; i < collect_input.s ize(); ++i)
std::cout << collect_input[i]
<< '\n';
A more idiomatic way of doing the above is to use std::copy:

std::copy( collect_input.b egin(), collect_input.e nd(),
ostream_iterato r<std::string> ( cout, "\n" ) );
return 0;
}
2 questions:

1.) why do i need to "copy" the whole vector ?

2.) is "std::cout" is less maintainable/readable than
"ostream_iterat or" ?

One last thing, I think you will find that the above program will print
words twice if they are entered twice. Look up std::set.
i tried std::set, it does not make any sense to me, as of now. it is
on page 491, section 17.4.3 of Stroustrup (special edition).
BTW, this is the best i have come up with:

--------- PROGRAMME ------------
/* Stroustrup, 5.9, exercise 11

STATEMENT:
Read a sequence of words from the input. use "quit" as the word
to terminate the input. Print the words in the order they were
entered. don't print a word twice.modify the programme to sort the
words before printing them.

*/

#include<iostre am>
#include<string >
#include<algori thm>
#include<vector >
#include<set>
#include<iterat or>

int main()
{
std::string input_word;
std::vector<std ::stringcollect _input, removed_duplica tes;

while(std::cin >input_word && input_word != "quit")
{
collect_input.p ush_back(input_ word);
}
std::cout << "\n *** Printing Sorted Words ***\n";

// sorting the input
sort(collect_in put.begin(), collect_input.e nd());
unique_copy(col lect_input.begi n(), collect_input.e nd(),
back_inserter(r emoved_duplicat es));

for(std::size_t i=0; i < removed_duplica tes.size(); ++i)
{
std::cout << removed_duplica tes[i] << '\n';
}

return 0;
}

---------- OUTPUT -------------
[arch@voodo tc++pl]$ g++ -ansi -pedantic -Wall -Wextra -O
ex_5.9-11_modified.cpp
[arch@voodo tc++pl]$ ./a.out
like this
and this
and this
done quit

*** Printing Sorted Words ***
and
done
like
this
[arch@voodo tc++pl]$ ./a.out

Apr 9 '07 #8
On Apr 9, 5:34 am, Zeppe <z...@email.itw rote:
>
Another note: if the performances are not a priority, it is better to
declare the variables as close as possible to the point in which they
are used.
What does "declaring variables close to first use" have to do with
performance?

- Anand

Apr 9 '07 #9
"arnuld" <ge*********@gm ail.comwrote:
On Apr 9, 4:38 pm, "Daniel T." <danie...@earth link.netwrote:
"arnuld" <geek.arn...@gm ail.comwrote:
std::cout << "\n *** Printing WOrds ***\n";
for(unsigned int i=0; i < collect_input.s ize(); ++i)
std::cout << collect_input[i]
<< '\n';

A more idiomatic way of doing the above is to use std::copy:

std::copy( collect_input.b egin(), collect_input.e nd(),
ostream_iterato r<std::string> ( cout, "\n" ) );
return 0;
}

2 questions:

1.) why do i need to "copy" the whole vector ?
You have to copy the whole vector to cout. That is what you are doing
when you print all the strings.
2.) is "std::cout" is less maintainable/readable than
"ostream_iterat or" ?
No, but the loop itself is.

for ( std::vector<std ::string>::iter ator i = collected_input .begin();
i != collected_input .end(); ++i )
{
cout << *i << '\n';
}

The above works, but if you decide to change the container to anything
other than a vector, you have to change the loop also.

for ( unsigned i = 0; i < collected_input .size(); ++i )
{
cout << collected_input[i] << '\n';
}

The above also works but only for vectors and deques, not for lists or
sets.
One last thing, I think you will find that the above program will print
words twice if they are entered twice. Look up std::set.

i tried std::set, it does not make any sense to me, as of now. it is
on page 491, section 17.4.3 of Stroustrup (special edition).
With std::set, you insert the item instead of using push_back and it
keeps the items sorted.
BTW, this is the best i have come up with:
What you came up with is great for satisfying the last sentence of the
requirement, but not the first 3.

The hardest part of this exorcise is to remove duplicates *without*
sorting the input.
Apr 9 '07 #10

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

Similar topics

26
3126
by: Oplec | last post by:
Hi, I am learning standard C++ as a hobby. The C++ Programming Language : Special Edition has been the principal source for my information. I read the entirety of the book and concluded that I had done myself a disservice by having not attempted and completed the exercises. I intend to rectify that. My current routine is to read a chapter...
7
2340
by: arnuld | last post by:
problem: define functions F(char), g(char&) & h(const char&). call them with arguments 'a', 49, 3300, c, uc & sc where c is a char, uc is unsigned char & sc is signed char. whihc calls are legal? which calls cause the compiler to to introduce a temporary variable? solution: this is the code...
0
1746
by: arnuld | last post by:
Stroustrup has a table in section 4.9 of declarations and definitions. he asks to write a similar table but in opposite sense: char ch; // declaration with definition he asks to do the opposite as an exercise which is writing it as a "declaration without definition". please check whether i am right or wrong:
0
1748
by: arnuld | last post by:
this programme runs without any trouble. it took 45 minutes of typing. i posted it here so that people can save their precious time: // Stroustrup special edition // chapter 4 exercise 2 // printing the sizes of different types
2
5329
by: arnuld | last post by:
MAX and MIN values of CHAR could not be displayed. Why ? BTW, any advice on improvement ? (please remember i have covered chapter 4 only) ------------- PROGRAMME -------------- /* Stroustrup 3e, section 4.11, exercise 5 STATEMENT:
16
2348
by: arnuld | last post by:
i did what i could do at Best to solve this exercise and this i what i have come up with: ----------- PROGRAMME -------------- /* Stroustrup 5.9, exercise 3 STATEMENT: Use typedef to define the types: unsigned char
11
1816
by: arnuld | last post by:
/* Stroustrup: 5.9 exercise 7 STATEMENTS: Define a table of the name sof months o fyear and the number of days in each month. write out that table. Do this twice: 1.) using ar array of char for names of months and an array of numbers for number of days. 2.) using an array of structures. each structure holds the name of the
6
3033
by: arnuld | last post by:
this one was much easier and works fine. as usual, i put code here for any further comments/views/advice: --------- PROGRAMME ------------ /* Stroustrup: 5.9 exercise 7 STATEMENTS: Define a table of the name sof months o fyear and the number of days in each month. write out that table. Do this twice:
14
2457
by: arnuld | last post by:
there is no "compile-time error". after i enter input and hit ENTER i get a run-time error. here is the code: ---------- PROGRAMME -------------- /* Stroustrup, 5.9, exercise 11 STATEMENT: Read a sequence of words from the input. use "quit" as the word
0
7665
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8106
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7642
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7950
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5484
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3643
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1200
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.