Overloading istream>> to read comma-separated input The Next CEO of Stack OverflowClass to read comma separated data from diskCalculator - C++ operator-overloadingSelecting results as a comma-separated stringCreating an istream peekerCustomized streambuffer for C++ istreamC++ operator overloading for matrix operationsC++ operator overloading for matrix operations - follow-upEncapsulation preserving operator= overloading in C++Operator Overloading Tricks in C++C++ Read istream into string with exceptions

Bartok - Syncopation (1): Meaning of notes in between Grand Staff

Are police here, aren't itthey?

Does increasing your ability score affect your main stat?

No sign flipping while figuring out the emf of voltaic cell?

Is there a difference between "Fahrstuhl" and "Aufzug"

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?

Why isn't acceleration always zero whenever velocity is zero, such as the moment a ball bounces off a wall?

Can MTA send mail via a relay without being told so?

How to avoid supervisors with prejudiced views?

Why is my new battery behaving weirdly?

Does Germany produce more waste than the US?

Why is information "lost" when it got into a black hole?

Is French Guiana a (hard) EU border?

What happened in Rome, when the western empire "fell"?

Newlines in BSD sed vs gsed

What flight has the highest ratio of time difference to flight time?

Why doesn't UK go for the same deal Japan has with EU to resolve Brexit?

What did we know about the Kessel run before the prequels?

Is it possible to replace duplicates of a character with one character using tr

Is there a way to save my career from absolute disaster?

Reference request: Grassmannian and Plucker coordinates in type B, C, D

Help understanding this unsettling image of Titan, Epimetheus, and Saturn's rings?

Running a General Election and the European Elections together



Overloading istream>> to read comma-separated input



The Next CEO of Stack OverflowClass to read comma separated data from diskCalculator - C++ operator-overloadingSelecting results as a comma-separated stringCreating an istream peekerCustomized streambuffer for C++ istreamC++ operator overloading for matrix operationsC++ operator overloading for matrix operations - follow-upEncapsulation preserving operator= overloading in C++Operator Overloading Tricks in C++C++ Read istream into string with exceptions










6












$begingroup$


I have the following very simple class:



class accusation

private:
std::string murderer;
std::string weapon;
std::string place;
public:
accusation() = default;
accusation(std::string, std::string, std::string);
friend std::ostream& operator<<(std::ostream&, const accusation&);
friend std::istream& operator>>(std::istream&, accusation&);
;


I have overloaded my extraction from istream operator as follows:



std::istream& operator>>(std::istream& is, accusation& readable)

std::vector<std::string> accusation;
std::string token, word;
//divide by commas
while (std::getline(is, token, ','))

std::string pushable;
std::stringstream ss(token);
while (ss >> word) pushable += word + " ";
if (pushable.size() != 0) pushable.pop_back(); //remove that last white space
std::transform(pushable.begin(), pushable.end(), pushable.begin(), ::tolower);
accusation.push_back(pushable);

if (accusation.size() == 3)

is.clear();
bool valid false ;
//check it matches one of the clue::characters
for (const auto& character : clue::characters)
if (accusation[0] == character)

valid = true;
break;

if (valid)

valid = false;
//check it matches one of the clue::weapons
for (const auto& weapon : clue::weapons)
if (accusation[1] == weapon)

valid = true;
break;

if (valid)

valid = false;
//check it matches one of the clue::places
for (const auto& place : clue::places)
if (accusation[2] == place)

valid = true;
break;

if (valid)

readable.murderer = accusation[0];
readable.weapon = accusation[1];
readable.place = accusation[2];

else
is.setstate(std::ios_base::failbit);

else
is.setstate(std::ios_base::failbit);

else
is.setstate(std::ios_base::failbit);

else
is.setstate(std::ios_base::failbit);
return is;



I am reading input as green, dagger, kitchen and storing it in my accusation. The first element has to be in clue::characters (an array of possible game characters), second element in clue::weapons, and third element in clue::places.



Can somebody suggest a cleaner way to overload this operator? The code works as expected, but I believe that there is a lot of space for improvements. Any push into the right direction is highly appreciated.










share|improve this question









New contributor




Daniel Duque is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$







  • 1




    $begingroup$
    Welcome to CR, Could you please change the title to show the requirement from business/exercise point of view rather than your concerns. Concerns should go into the body of the question. :)
    $endgroup$
    – 422_unprocessable_entity
    Mar 27 at 15:43















6












$begingroup$


I have the following very simple class:



class accusation

private:
std::string murderer;
std::string weapon;
std::string place;
public:
accusation() = default;
accusation(std::string, std::string, std::string);
friend std::ostream& operator<<(std::ostream&, const accusation&);
friend std::istream& operator>>(std::istream&, accusation&);
;


I have overloaded my extraction from istream operator as follows:



std::istream& operator>>(std::istream& is, accusation& readable)

std::vector<std::string> accusation;
std::string token, word;
//divide by commas
while (std::getline(is, token, ','))

std::string pushable;
std::stringstream ss(token);
while (ss >> word) pushable += word + " ";
if (pushable.size() != 0) pushable.pop_back(); //remove that last white space
std::transform(pushable.begin(), pushable.end(), pushable.begin(), ::tolower);
accusation.push_back(pushable);

if (accusation.size() == 3)

is.clear();
bool valid false ;
//check it matches one of the clue::characters
for (const auto& character : clue::characters)
if (accusation[0] == character)

valid = true;
break;

if (valid)

valid = false;
//check it matches one of the clue::weapons
for (const auto& weapon : clue::weapons)
if (accusation[1] == weapon)

valid = true;
break;

if (valid)

valid = false;
//check it matches one of the clue::places
for (const auto& place : clue::places)
if (accusation[2] == place)

valid = true;
break;

if (valid)

readable.murderer = accusation[0];
readable.weapon = accusation[1];
readable.place = accusation[2];

else
is.setstate(std::ios_base::failbit);

else
is.setstate(std::ios_base::failbit);

else
is.setstate(std::ios_base::failbit);

else
is.setstate(std::ios_base::failbit);
return is;



I am reading input as green, dagger, kitchen and storing it in my accusation. The first element has to be in clue::characters (an array of possible game characters), second element in clue::weapons, and third element in clue::places.



Can somebody suggest a cleaner way to overload this operator? The code works as expected, but I believe that there is a lot of space for improvements. Any push into the right direction is highly appreciated.










share|improve this question









New contributor




Daniel Duque is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$







  • 1




    $begingroup$
    Welcome to CR, Could you please change the title to show the requirement from business/exercise point of view rather than your concerns. Concerns should go into the body of the question. :)
    $endgroup$
    – 422_unprocessable_entity
    Mar 27 at 15:43













6












6








6


1



$begingroup$


I have the following very simple class:



class accusation

private:
std::string murderer;
std::string weapon;
std::string place;
public:
accusation() = default;
accusation(std::string, std::string, std::string);
friend std::ostream& operator<<(std::ostream&, const accusation&);
friend std::istream& operator>>(std::istream&, accusation&);
;


I have overloaded my extraction from istream operator as follows:



std::istream& operator>>(std::istream& is, accusation& readable)

std::vector<std::string> accusation;
std::string token, word;
//divide by commas
while (std::getline(is, token, ','))

std::string pushable;
std::stringstream ss(token);
while (ss >> word) pushable += word + " ";
if (pushable.size() != 0) pushable.pop_back(); //remove that last white space
std::transform(pushable.begin(), pushable.end(), pushable.begin(), ::tolower);
accusation.push_back(pushable);

if (accusation.size() == 3)

is.clear();
bool valid false ;
//check it matches one of the clue::characters
for (const auto& character : clue::characters)
if (accusation[0] == character)

valid = true;
break;

if (valid)

valid = false;
//check it matches one of the clue::weapons
for (const auto& weapon : clue::weapons)
if (accusation[1] == weapon)

valid = true;
break;

if (valid)

valid = false;
//check it matches one of the clue::places
for (const auto& place : clue::places)
if (accusation[2] == place)

valid = true;
break;

if (valid)

readable.murderer = accusation[0];
readable.weapon = accusation[1];
readable.place = accusation[2];

else
is.setstate(std::ios_base::failbit);

else
is.setstate(std::ios_base::failbit);

else
is.setstate(std::ios_base::failbit);

else
is.setstate(std::ios_base::failbit);
return is;



I am reading input as green, dagger, kitchen and storing it in my accusation. The first element has to be in clue::characters (an array of possible game characters), second element in clue::weapons, and third element in clue::places.



Can somebody suggest a cleaner way to overload this operator? The code works as expected, but I believe that there is a lot of space for improvements. Any push into the right direction is highly appreciated.










share|improve this question









New contributor




Daniel Duque is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$




I have the following very simple class:



class accusation

private:
std::string murderer;
std::string weapon;
std::string place;
public:
accusation() = default;
accusation(std::string, std::string, std::string);
friend std::ostream& operator<<(std::ostream&, const accusation&);
friend std::istream& operator>>(std::istream&, accusation&);
;


I have overloaded my extraction from istream operator as follows:



std::istream& operator>>(std::istream& is, accusation& readable)

std::vector<std::string> accusation;
std::string token, word;
//divide by commas
while (std::getline(is, token, ','))

std::string pushable;
std::stringstream ss(token);
while (ss >> word) pushable += word + " ";
if (pushable.size() != 0) pushable.pop_back(); //remove that last white space
std::transform(pushable.begin(), pushable.end(), pushable.begin(), ::tolower);
accusation.push_back(pushable);

if (accusation.size() == 3)

is.clear();
bool valid false ;
//check it matches one of the clue::characters
for (const auto& character : clue::characters)
if (accusation[0] == character)

valid = true;
break;

if (valid)

valid = false;
//check it matches one of the clue::weapons
for (const auto& weapon : clue::weapons)
if (accusation[1] == weapon)

valid = true;
break;

if (valid)

valid = false;
//check it matches one of the clue::places
for (const auto& place : clue::places)
if (accusation[2] == place)

valid = true;
break;

if (valid)

readable.murderer = accusation[0];
readable.weapon = accusation[1];
readable.place = accusation[2];

else
is.setstate(std::ios_base::failbit);

else
is.setstate(std::ios_base::failbit);

else
is.setstate(std::ios_base::failbit);

else
is.setstate(std::ios_base::failbit);
return is;



I am reading input as green, dagger, kitchen and storing it in my accusation. The first element has to be in clue::characters (an array of possible game characters), second element in clue::weapons, and third element in clue::places.



Can somebody suggest a cleaner way to overload this operator? The code works as expected, but I believe that there is a lot of space for improvements. Any push into the right direction is highly appreciated.







c++ beginner parsing stream overloading






share|improve this question









New contributor




Daniel Duque is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Daniel Duque is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Mar 27 at 16:39







Daniel Duque













New contributor




Daniel Duque is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Mar 27 at 14:20









Daniel DuqueDaniel Duque

555




555




New contributor




Daniel Duque is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Daniel Duque is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Daniel Duque is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 1




    $begingroup$
    Welcome to CR, Could you please change the title to show the requirement from business/exercise point of view rather than your concerns. Concerns should go into the body of the question. :)
    $endgroup$
    – 422_unprocessable_entity
    Mar 27 at 15:43












  • 1




    $begingroup$
    Welcome to CR, Could you please change the title to show the requirement from business/exercise point of view rather than your concerns. Concerns should go into the body of the question. :)
    $endgroup$
    – 422_unprocessable_entity
    Mar 27 at 15:43







1




1




$begingroup$
Welcome to CR, Could you please change the title to show the requirement from business/exercise point of view rather than your concerns. Concerns should go into the body of the question. :)
$endgroup$
– 422_unprocessable_entity
Mar 27 at 15:43




$begingroup$
Welcome to CR, Could you please change the title to show the requirement from business/exercise point of view rather than your concerns. Concerns should go into the body of the question. :)
$endgroup$
– 422_unprocessable_entity
Mar 27 at 15:43










1 Answer
1






active

oldest

votes


















7












$begingroup$

95 percent of programming is looking for redundancies and eliminating them.



For example, why do you bother with reading strings into accusations[] first, and then later copying them into readable.murderer et cetera? Why not just read them directly into readable.murderer? This would have the bonus of eliminating those "magic number" indices 0, 1, and 2, and replacing them with readable (no pun intended) identifiers.



std::getline(is, readable.murderer, ',');
std::getline(is, readable.weapon, ',');
std::getline(is, readable.place, ','); // shouldn't this last one be 'n' not ','?


You should test your code and see if it does what you wanted.



std::istringstream iss(
"Mr Green, lead pipe, conservatoryn"
"Mrs Peacock, noose, kitchen"
);
accusation acc;
iss >> acc;


This reads 5 items into accusation. Is this what you wanted to happen?




Reduce repetition. You have the following snippet repeated three times:



 for (const auto& THING : THINGS)
if (accusation[INDEX] == THING)

valid = true;
break;



So, first of all, we wrap the loop body in curly braces to protect against goto fail; and then we factor it out into a function.



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
for (auto&& elt : vec)
if (elt == value)
return true;


return false;



And then our main function's code can become simply



bool valid = vector_contains(clue::characters, readable.murderer)
&& vector_contains(clue::weapons, readable.weapon)
&& vector_contains(clue::places, readable.place);
if (!valid)
is.setstate(std::ios_base::failbit);




The body of vector_contains could also be implemented simply by using an STL algorithm, e.g.



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::count(vec.begin(), vec.end(), value);



or



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::find(vec.begin(), vec.end(), value) != vec.end();



or



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::any_of(vec.begin(), vec.end(), [&](const auto& elt)
return elt == value;
);



I named the function vector_contains, rather than simply contains, because in my estimation there is a very real possibility that C++2a might add std::contains to the library and thus break any code using ADL calls to contains.




Minor nits:



  • I strongly recommend making all your constructors explicit, to eliminate bugs from unintentional implicit conversions. (Yes, even your multi-argument constructors.)


  • I strongly recommend making operator>> and operator<< into inline friend functions — define them right inside the body of your class. This will make them findable only via ADL, and is generally what you want. It'll look a lot more reasonable, too, once you've refactored your operator>> to be only five or six lines long! :)



You're also doing something weird with stringstream to remove whitespace from the ends of each piece of the string. You should factor that out into a helper function, and then simplify it. Say,



std::string strip(const std::string& s)

int i = 0;
while (isspace(s[i])) ++i;
int j = s.size();
while (j >= 1 && isspace(s[j-1])) --j;
return s.substr(i, j-i);



https://wandbox.org/permlink/uVSolN0Nepk48Mgm



class accusation

private:
std::string murderer;
std::string weapon;
std::string place;
public:
accusation() = default;
explicit accusation(std::string, std::string, std::string);
friend std::ostream& operator<<(std::ostream&, const accusation&);
friend std::istream& operator>>(std::istream& is, accusation& a)
;


Deciding whether your std::transform lowercasing should be removed, kept, or folded into the helper function vector_contains (renaming that function to indicate its new purpose, and using a non-mutating facility such as strcasecmp) is left as an exercise for the reader.






share|improve this answer









$endgroup$












  • $begingroup$
    Thanks for all your feedback, it has been very eye-opening reading all your suggestions. Regarding your 'strip' function, it only removes white spaces from the beginning and the end of a string; opposed to what I was doing which deleted extra white space between words as well. Nevertheless I get your point, and will improve my code from all your suggestions.
    $endgroup$
    – Daniel Duque
    Mar 27 at 17:01






  • 1




    $begingroup$
    Given that you made mr green acceptable as a synonym for Mr Green, maybe you should consider whether mrgreen should be acceptable as well. Then you wouldn't even need to remove spaces; you could just write a non-mutating string comparison, similar to strcasecmp, that ignores all whitespace too. Personally, I would go the other direction and force the user to enter Mr Green using that one exact spelling, to increase simplicity and ease-of-teaching-the-interface. If you do want to do clever fuzzy matching, look at en.wikipedia.org/wiki/Approximate_string_matching for ideas.
    $endgroup$
    – Quuxplusone
    Mar 27 at 17:25











  • $begingroup$
    Writing directly into the object means you lose the strong exception guarantee. You also risk creating invalid accusation objects with broken invariants. Writing into a temp object then moving into a, or, even better, writing into three strings then doing validation on them (using a function you should already have for validating the constructor args), is a better plan.
    $endgroup$
    – indi
    23 hours ago











Your Answer





StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");

StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);






Daniel Duque is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216343%2foverloading-istream-to-read-comma-separated-input%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









7












$begingroup$

95 percent of programming is looking for redundancies and eliminating them.



For example, why do you bother with reading strings into accusations[] first, and then later copying them into readable.murderer et cetera? Why not just read them directly into readable.murderer? This would have the bonus of eliminating those "magic number" indices 0, 1, and 2, and replacing them with readable (no pun intended) identifiers.



std::getline(is, readable.murderer, ',');
std::getline(is, readable.weapon, ',');
std::getline(is, readable.place, ','); // shouldn't this last one be 'n' not ','?


You should test your code and see if it does what you wanted.



std::istringstream iss(
"Mr Green, lead pipe, conservatoryn"
"Mrs Peacock, noose, kitchen"
);
accusation acc;
iss >> acc;


This reads 5 items into accusation. Is this what you wanted to happen?




Reduce repetition. You have the following snippet repeated three times:



 for (const auto& THING : THINGS)
if (accusation[INDEX] == THING)

valid = true;
break;



So, first of all, we wrap the loop body in curly braces to protect against goto fail; and then we factor it out into a function.



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
for (auto&& elt : vec)
if (elt == value)
return true;


return false;



And then our main function's code can become simply



bool valid = vector_contains(clue::characters, readable.murderer)
&& vector_contains(clue::weapons, readable.weapon)
&& vector_contains(clue::places, readable.place);
if (!valid)
is.setstate(std::ios_base::failbit);




The body of vector_contains could also be implemented simply by using an STL algorithm, e.g.



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::count(vec.begin(), vec.end(), value);



or



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::find(vec.begin(), vec.end(), value) != vec.end();



or



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::any_of(vec.begin(), vec.end(), [&](const auto& elt)
return elt == value;
);



I named the function vector_contains, rather than simply contains, because in my estimation there is a very real possibility that C++2a might add std::contains to the library and thus break any code using ADL calls to contains.




Minor nits:



  • I strongly recommend making all your constructors explicit, to eliminate bugs from unintentional implicit conversions. (Yes, even your multi-argument constructors.)


  • I strongly recommend making operator>> and operator<< into inline friend functions — define them right inside the body of your class. This will make them findable only via ADL, and is generally what you want. It'll look a lot more reasonable, too, once you've refactored your operator>> to be only five or six lines long! :)



You're also doing something weird with stringstream to remove whitespace from the ends of each piece of the string. You should factor that out into a helper function, and then simplify it. Say,



std::string strip(const std::string& s)

int i = 0;
while (isspace(s[i])) ++i;
int j = s.size();
while (j >= 1 && isspace(s[j-1])) --j;
return s.substr(i, j-i);



https://wandbox.org/permlink/uVSolN0Nepk48Mgm



class accusation

private:
std::string murderer;
std::string weapon;
std::string place;
public:
accusation() = default;
explicit accusation(std::string, std::string, std::string);
friend std::ostream& operator<<(std::ostream&, const accusation&);
friend std::istream& operator>>(std::istream& is, accusation& a)
;


Deciding whether your std::transform lowercasing should be removed, kept, or folded into the helper function vector_contains (renaming that function to indicate its new purpose, and using a non-mutating facility such as strcasecmp) is left as an exercise for the reader.






share|improve this answer









$endgroup$












  • $begingroup$
    Thanks for all your feedback, it has been very eye-opening reading all your suggestions. Regarding your 'strip' function, it only removes white spaces from the beginning and the end of a string; opposed to what I was doing which deleted extra white space between words as well. Nevertheless I get your point, and will improve my code from all your suggestions.
    $endgroup$
    – Daniel Duque
    Mar 27 at 17:01






  • 1




    $begingroup$
    Given that you made mr green acceptable as a synonym for Mr Green, maybe you should consider whether mrgreen should be acceptable as well. Then you wouldn't even need to remove spaces; you could just write a non-mutating string comparison, similar to strcasecmp, that ignores all whitespace too. Personally, I would go the other direction and force the user to enter Mr Green using that one exact spelling, to increase simplicity and ease-of-teaching-the-interface. If you do want to do clever fuzzy matching, look at en.wikipedia.org/wiki/Approximate_string_matching for ideas.
    $endgroup$
    – Quuxplusone
    Mar 27 at 17:25











  • $begingroup$
    Writing directly into the object means you lose the strong exception guarantee. You also risk creating invalid accusation objects with broken invariants. Writing into a temp object then moving into a, or, even better, writing into three strings then doing validation on them (using a function you should already have for validating the constructor args), is a better plan.
    $endgroup$
    – indi
    23 hours ago















7












$begingroup$

95 percent of programming is looking for redundancies and eliminating them.



For example, why do you bother with reading strings into accusations[] first, and then later copying them into readable.murderer et cetera? Why not just read them directly into readable.murderer? This would have the bonus of eliminating those "magic number" indices 0, 1, and 2, and replacing them with readable (no pun intended) identifiers.



std::getline(is, readable.murderer, ',');
std::getline(is, readable.weapon, ',');
std::getline(is, readable.place, ','); // shouldn't this last one be 'n' not ','?


You should test your code and see if it does what you wanted.



std::istringstream iss(
"Mr Green, lead pipe, conservatoryn"
"Mrs Peacock, noose, kitchen"
);
accusation acc;
iss >> acc;


This reads 5 items into accusation. Is this what you wanted to happen?




Reduce repetition. You have the following snippet repeated three times:



 for (const auto& THING : THINGS)
if (accusation[INDEX] == THING)

valid = true;
break;



So, first of all, we wrap the loop body in curly braces to protect against goto fail; and then we factor it out into a function.



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
for (auto&& elt : vec)
if (elt == value)
return true;


return false;



And then our main function's code can become simply



bool valid = vector_contains(clue::characters, readable.murderer)
&& vector_contains(clue::weapons, readable.weapon)
&& vector_contains(clue::places, readable.place);
if (!valid)
is.setstate(std::ios_base::failbit);




The body of vector_contains could also be implemented simply by using an STL algorithm, e.g.



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::count(vec.begin(), vec.end(), value);



or



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::find(vec.begin(), vec.end(), value) != vec.end();



or



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::any_of(vec.begin(), vec.end(), [&](const auto& elt)
return elt == value;
);



I named the function vector_contains, rather than simply contains, because in my estimation there is a very real possibility that C++2a might add std::contains to the library and thus break any code using ADL calls to contains.




Minor nits:



  • I strongly recommend making all your constructors explicit, to eliminate bugs from unintentional implicit conversions. (Yes, even your multi-argument constructors.)


  • I strongly recommend making operator>> and operator<< into inline friend functions — define them right inside the body of your class. This will make them findable only via ADL, and is generally what you want. It'll look a lot more reasonable, too, once you've refactored your operator>> to be only five or six lines long! :)



You're also doing something weird with stringstream to remove whitespace from the ends of each piece of the string. You should factor that out into a helper function, and then simplify it. Say,



std::string strip(const std::string& s)

int i = 0;
while (isspace(s[i])) ++i;
int j = s.size();
while (j >= 1 && isspace(s[j-1])) --j;
return s.substr(i, j-i);



https://wandbox.org/permlink/uVSolN0Nepk48Mgm



class accusation

private:
std::string murderer;
std::string weapon;
std::string place;
public:
accusation() = default;
explicit accusation(std::string, std::string, std::string);
friend std::ostream& operator<<(std::ostream&, const accusation&);
friend std::istream& operator>>(std::istream& is, accusation& a)
;


Deciding whether your std::transform lowercasing should be removed, kept, or folded into the helper function vector_contains (renaming that function to indicate its new purpose, and using a non-mutating facility such as strcasecmp) is left as an exercise for the reader.






share|improve this answer









$endgroup$












  • $begingroup$
    Thanks for all your feedback, it has been very eye-opening reading all your suggestions. Regarding your 'strip' function, it only removes white spaces from the beginning and the end of a string; opposed to what I was doing which deleted extra white space between words as well. Nevertheless I get your point, and will improve my code from all your suggestions.
    $endgroup$
    – Daniel Duque
    Mar 27 at 17:01






  • 1




    $begingroup$
    Given that you made mr green acceptable as a synonym for Mr Green, maybe you should consider whether mrgreen should be acceptable as well. Then you wouldn't even need to remove spaces; you could just write a non-mutating string comparison, similar to strcasecmp, that ignores all whitespace too. Personally, I would go the other direction and force the user to enter Mr Green using that one exact spelling, to increase simplicity and ease-of-teaching-the-interface. If you do want to do clever fuzzy matching, look at en.wikipedia.org/wiki/Approximate_string_matching for ideas.
    $endgroup$
    – Quuxplusone
    Mar 27 at 17:25











  • $begingroup$
    Writing directly into the object means you lose the strong exception guarantee. You also risk creating invalid accusation objects with broken invariants. Writing into a temp object then moving into a, or, even better, writing into three strings then doing validation on them (using a function you should already have for validating the constructor args), is a better plan.
    $endgroup$
    – indi
    23 hours ago













7












7








7





$begingroup$

95 percent of programming is looking for redundancies and eliminating them.



For example, why do you bother with reading strings into accusations[] first, and then later copying them into readable.murderer et cetera? Why not just read them directly into readable.murderer? This would have the bonus of eliminating those "magic number" indices 0, 1, and 2, and replacing them with readable (no pun intended) identifiers.



std::getline(is, readable.murderer, ',');
std::getline(is, readable.weapon, ',');
std::getline(is, readable.place, ','); // shouldn't this last one be 'n' not ','?


You should test your code and see if it does what you wanted.



std::istringstream iss(
"Mr Green, lead pipe, conservatoryn"
"Mrs Peacock, noose, kitchen"
);
accusation acc;
iss >> acc;


This reads 5 items into accusation. Is this what you wanted to happen?




Reduce repetition. You have the following snippet repeated three times:



 for (const auto& THING : THINGS)
if (accusation[INDEX] == THING)

valid = true;
break;



So, first of all, we wrap the loop body in curly braces to protect against goto fail; and then we factor it out into a function.



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
for (auto&& elt : vec)
if (elt == value)
return true;


return false;



And then our main function's code can become simply



bool valid = vector_contains(clue::characters, readable.murderer)
&& vector_contains(clue::weapons, readable.weapon)
&& vector_contains(clue::places, readable.place);
if (!valid)
is.setstate(std::ios_base::failbit);




The body of vector_contains could also be implemented simply by using an STL algorithm, e.g.



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::count(vec.begin(), vec.end(), value);



or



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::find(vec.begin(), vec.end(), value) != vec.end();



or



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::any_of(vec.begin(), vec.end(), [&](const auto& elt)
return elt == value;
);



I named the function vector_contains, rather than simply contains, because in my estimation there is a very real possibility that C++2a might add std::contains to the library and thus break any code using ADL calls to contains.




Minor nits:



  • I strongly recommend making all your constructors explicit, to eliminate bugs from unintentional implicit conversions. (Yes, even your multi-argument constructors.)


  • I strongly recommend making operator>> and operator<< into inline friend functions — define them right inside the body of your class. This will make them findable only via ADL, and is generally what you want. It'll look a lot more reasonable, too, once you've refactored your operator>> to be only five or six lines long! :)



You're also doing something weird with stringstream to remove whitespace from the ends of each piece of the string. You should factor that out into a helper function, and then simplify it. Say,



std::string strip(const std::string& s)

int i = 0;
while (isspace(s[i])) ++i;
int j = s.size();
while (j >= 1 && isspace(s[j-1])) --j;
return s.substr(i, j-i);



https://wandbox.org/permlink/uVSolN0Nepk48Mgm



class accusation

private:
std::string murderer;
std::string weapon;
std::string place;
public:
accusation() = default;
explicit accusation(std::string, std::string, std::string);
friend std::ostream& operator<<(std::ostream&, const accusation&);
friend std::istream& operator>>(std::istream& is, accusation& a)
;


Deciding whether your std::transform lowercasing should be removed, kept, or folded into the helper function vector_contains (renaming that function to indicate its new purpose, and using a non-mutating facility such as strcasecmp) is left as an exercise for the reader.






share|improve this answer









$endgroup$



95 percent of programming is looking for redundancies and eliminating them.



For example, why do you bother with reading strings into accusations[] first, and then later copying them into readable.murderer et cetera? Why not just read them directly into readable.murderer? This would have the bonus of eliminating those "magic number" indices 0, 1, and 2, and replacing them with readable (no pun intended) identifiers.



std::getline(is, readable.murderer, ',');
std::getline(is, readable.weapon, ',');
std::getline(is, readable.place, ','); // shouldn't this last one be 'n' not ','?


You should test your code and see if it does what you wanted.



std::istringstream iss(
"Mr Green, lead pipe, conservatoryn"
"Mrs Peacock, noose, kitchen"
);
accusation acc;
iss >> acc;


This reads 5 items into accusation. Is this what you wanted to happen?




Reduce repetition. You have the following snippet repeated three times:



 for (const auto& THING : THINGS)
if (accusation[INDEX] == THING)

valid = true;
break;



So, first of all, we wrap the loop body in curly braces to protect against goto fail; and then we factor it out into a function.



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
for (auto&& elt : vec)
if (elt == value)
return true;


return false;



And then our main function's code can become simply



bool valid = vector_contains(clue::characters, readable.murderer)
&& vector_contains(clue::weapons, readable.weapon)
&& vector_contains(clue::places, readable.place);
if (!valid)
is.setstate(std::ios_base::failbit);




The body of vector_contains could also be implemented simply by using an STL algorithm, e.g.



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::count(vec.begin(), vec.end(), value);



or



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::find(vec.begin(), vec.end(), value) != vec.end();



or



template<class T>
bool vector_contains(const std::vector<T>& vec, const T& value)
return std::any_of(vec.begin(), vec.end(), [&](const auto& elt)
return elt == value;
);



I named the function vector_contains, rather than simply contains, because in my estimation there is a very real possibility that C++2a might add std::contains to the library and thus break any code using ADL calls to contains.




Minor nits:



  • I strongly recommend making all your constructors explicit, to eliminate bugs from unintentional implicit conversions. (Yes, even your multi-argument constructors.)


  • I strongly recommend making operator>> and operator<< into inline friend functions — define them right inside the body of your class. This will make them findable only via ADL, and is generally what you want. It'll look a lot more reasonable, too, once you've refactored your operator>> to be only five or six lines long! :)



You're also doing something weird with stringstream to remove whitespace from the ends of each piece of the string. You should factor that out into a helper function, and then simplify it. Say,



std::string strip(const std::string& s)

int i = 0;
while (isspace(s[i])) ++i;
int j = s.size();
while (j >= 1 && isspace(s[j-1])) --j;
return s.substr(i, j-i);



https://wandbox.org/permlink/uVSolN0Nepk48Mgm



class accusation

private:
std::string murderer;
std::string weapon;
std::string place;
public:
accusation() = default;
explicit accusation(std::string, std::string, std::string);
friend std::ostream& operator<<(std::ostream&, const accusation&);
friend std::istream& operator>>(std::istream& is, accusation& a)
;


Deciding whether your std::transform lowercasing should be removed, kept, or folded into the helper function vector_contains (renaming that function to indicate its new purpose, and using a non-mutating facility such as strcasecmp) is left as an exercise for the reader.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 27 at 15:39









QuuxplusoneQuuxplusone

12.8k12062




12.8k12062











  • $begingroup$
    Thanks for all your feedback, it has been very eye-opening reading all your suggestions. Regarding your 'strip' function, it only removes white spaces from the beginning and the end of a string; opposed to what I was doing which deleted extra white space between words as well. Nevertheless I get your point, and will improve my code from all your suggestions.
    $endgroup$
    – Daniel Duque
    Mar 27 at 17:01






  • 1




    $begingroup$
    Given that you made mr green acceptable as a synonym for Mr Green, maybe you should consider whether mrgreen should be acceptable as well. Then you wouldn't even need to remove spaces; you could just write a non-mutating string comparison, similar to strcasecmp, that ignores all whitespace too. Personally, I would go the other direction and force the user to enter Mr Green using that one exact spelling, to increase simplicity and ease-of-teaching-the-interface. If you do want to do clever fuzzy matching, look at en.wikipedia.org/wiki/Approximate_string_matching for ideas.
    $endgroup$
    – Quuxplusone
    Mar 27 at 17:25











  • $begingroup$
    Writing directly into the object means you lose the strong exception guarantee. You also risk creating invalid accusation objects with broken invariants. Writing into a temp object then moving into a, or, even better, writing into three strings then doing validation on them (using a function you should already have for validating the constructor args), is a better plan.
    $endgroup$
    – indi
    23 hours ago
















  • $begingroup$
    Thanks for all your feedback, it has been very eye-opening reading all your suggestions. Regarding your 'strip' function, it only removes white spaces from the beginning and the end of a string; opposed to what I was doing which deleted extra white space between words as well. Nevertheless I get your point, and will improve my code from all your suggestions.
    $endgroup$
    – Daniel Duque
    Mar 27 at 17:01






  • 1




    $begingroup$
    Given that you made mr green acceptable as a synonym for Mr Green, maybe you should consider whether mrgreen should be acceptable as well. Then you wouldn't even need to remove spaces; you could just write a non-mutating string comparison, similar to strcasecmp, that ignores all whitespace too. Personally, I would go the other direction and force the user to enter Mr Green using that one exact spelling, to increase simplicity and ease-of-teaching-the-interface. If you do want to do clever fuzzy matching, look at en.wikipedia.org/wiki/Approximate_string_matching for ideas.
    $endgroup$
    – Quuxplusone
    Mar 27 at 17:25











  • $begingroup$
    Writing directly into the object means you lose the strong exception guarantee. You also risk creating invalid accusation objects with broken invariants. Writing into a temp object then moving into a, or, even better, writing into three strings then doing validation on them (using a function you should already have for validating the constructor args), is a better plan.
    $endgroup$
    – indi
    23 hours ago















$begingroup$
Thanks for all your feedback, it has been very eye-opening reading all your suggestions. Regarding your 'strip' function, it only removes white spaces from the beginning and the end of a string; opposed to what I was doing which deleted extra white space between words as well. Nevertheless I get your point, and will improve my code from all your suggestions.
$endgroup$
– Daniel Duque
Mar 27 at 17:01




$begingroup$
Thanks for all your feedback, it has been very eye-opening reading all your suggestions. Regarding your 'strip' function, it only removes white spaces from the beginning and the end of a string; opposed to what I was doing which deleted extra white space between words as well. Nevertheless I get your point, and will improve my code from all your suggestions.
$endgroup$
– Daniel Duque
Mar 27 at 17:01




1




1




$begingroup$
Given that you made mr green acceptable as a synonym for Mr Green, maybe you should consider whether mrgreen should be acceptable as well. Then you wouldn't even need to remove spaces; you could just write a non-mutating string comparison, similar to strcasecmp, that ignores all whitespace too. Personally, I would go the other direction and force the user to enter Mr Green using that one exact spelling, to increase simplicity and ease-of-teaching-the-interface. If you do want to do clever fuzzy matching, look at en.wikipedia.org/wiki/Approximate_string_matching for ideas.
$endgroup$
– Quuxplusone
Mar 27 at 17:25





$begingroup$
Given that you made mr green acceptable as a synonym for Mr Green, maybe you should consider whether mrgreen should be acceptable as well. Then you wouldn't even need to remove spaces; you could just write a non-mutating string comparison, similar to strcasecmp, that ignores all whitespace too. Personally, I would go the other direction and force the user to enter Mr Green using that one exact spelling, to increase simplicity and ease-of-teaching-the-interface. If you do want to do clever fuzzy matching, look at en.wikipedia.org/wiki/Approximate_string_matching for ideas.
$endgroup$
– Quuxplusone
Mar 27 at 17:25













$begingroup$
Writing directly into the object means you lose the strong exception guarantee. You also risk creating invalid accusation objects with broken invariants. Writing into a temp object then moving into a, or, even better, writing into three strings then doing validation on them (using a function you should already have for validating the constructor args), is a better plan.
$endgroup$
– indi
23 hours ago




$begingroup$
Writing directly into the object means you lose the strong exception guarantee. You also risk creating invalid accusation objects with broken invariants. Writing into a temp object then moving into a, or, even better, writing into three strings then doing validation on them (using a function you should already have for validating the constructor args), is a better plan.
$endgroup$
– indi
23 hours ago










Daniel Duque is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















Daniel Duque is a new contributor. Be nice, and check out our Code of Conduct.












Daniel Duque is a new contributor. Be nice, and check out our Code of Conduct.











Daniel Duque is a new contributor. Be nice, and check out our Code of Conduct.














Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216343%2foverloading-istream-to-read-comma-separated-input%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Boston (Lincolnshire) Stedsbyld | Berne yn Boston | NavigaasjemenuBoston Borough CouncilBoston, Lincolnshire

Ballerup Komuun Stääden an saarpen | Futnuuten | Luke uk diar | Nawigatsjuunwww.ballerup.dkwww.statistikbanken.dk: Tabelle BEF44 (Folketal pr. 1. januar fordelt på byer)Commonskategorii: Ballerup Komuun55° 44′ N, 12° 22′ O

Serbia Índice Etimología Historia Geografía Entorno natural División administrativa Política Demografía Economía Cultura Deportes Véase también Notas Referencias Bibliografía Enlaces externos Menú de navegación44°49′00″N 20°28′00″E / 44.816666666667, 20.46666666666744°49′00″N 20°28′00″E / 44.816666666667, 20.466666666667U.S. Department of Commerce (2015)«Informe sobre Desarrollo Humano 2018»Kosovo-Metohija.Neutralna Srbija u NATO okruzenju.The SerbsTheories on the Origin of the Serbs.Serbia.Earls: Webster's Quotations, Facts and Phrases.Egeo y Balcanes.Kalemegdan.Southern Pannonia during the age of the Great Migrations.Culture in Serbia.History.The Serbian Origin of the Montenegrins.Nemanjics' period (1186-1353).Stefan Uros (1355-1371).Serbian medieval history.Habsburg–Ottoman Wars (1525–1718).The Ottoman Empire, 1700-1922.The First Serbian Uprising.Miloš, prince of Serbia.3. Bosnia-Hercegovina and the Congress of Berlin.The Balkan Wars and the Partition of Macedonia.The Falcon and the Eagle: Montenegro and Austria-Hungary, 1908-1914.Typhus fever on the eastern front in World War I.Anniversary of WWI battle marked in Serbia.La derrota austriaca en los Balcanes. Fin del Imperio Austro-Húngaro.Imperio austriaco y Reino de Hungría.Los tiempos modernos: del capitalismo a la globalización, siglos XVII al XXI.The period of Croatia within ex-Yugoslavia.Yugoslavia: Much in a Name.Las dictaduras europeas.Croacia: mito y realidad."Crods ask arms".Prólogo a la invasión.La campaña de los Balcanes.La resistencia en Yugoslavia.Jasenovac Research Institute.Día en memoria de las víctimas del genocidio en la Segunda Guerra Mundial.El infierno estuvo en Jasenovac.Croacia empieza a «desenterrar» a sus muertos de Jasenovac.World fascism: a historical encyclopedia, Volumen 1.Tito. Josip Broz.El nuevo orden y la resistencia.La conquista del poder.Algunos aspectos de la economía yugoslava a mediados de 1962.Albania-Kosovo crisis.De Kosovo a Kosova: una visión demográfica.La crisis de la economía yugoslava y la política de "estabilización".Milosevic: el poder de un absolutista."Serbia under Milošević: politics in the 1990s"Milosevic cavó en Kosovo la tumba de la antigua Yugoslavia.La ONU exculpa a Serbia de genocidio en la guerra de Bosnia.Slobodan Milosevic, el burócrata que supo usar el odio.Es la fuerza contra el sufrimiento de muchos inocentes.Matanza de civiles al bombardear la OTAN un puente mientras pasaba un tren.Las consecuencias negativas de los bombardeos de Yugoslavia se sentirán aún durante largo tiempo.Kostunica advierte que la misión de Europa en Kosovo es ilegal.Las 24 horas más largas en la vida de Slobodan Milosevic.Serbia declara la guerra a la mafia por matar a Djindjic.Tadic presentará "quizás en diciembre" la solicitud de entrada en la UE.Montenegro declara su independencia de Serbia.Serbia se declara estado soberano tras separación de Montenegro.«Accordance with International Law of the Unilateral Declaration of Independence by the Provisional Institutions of Self-Government of Kosovo (Request for Advisory Opinion)»Mladic pasa por el médico antes de la audiencia para extraditarloDatos de Serbia y Kosovo.The Carpathian Mountains.Position, Relief, Climate.Transport.Finding birds in Serbia.U Srbiji do 2010. godine 10% teritorije nacionalni parkovi.Geography.Serbia: Climate.Variability of Climate In Serbia In The Second Half of The 20thc Entury.BASIC CLIMATE CHARACTERISTICS FOR THE TERRITORY OF SERBIA.Fauna y flora: Serbia.Serbia and Montenegro.Información general sobre Serbia.Republic of Serbia Environmental Protection Agency (SEPA).Serbia recycling 15% of waste.Reform process of the Serbian energy sector.20-MW Wind Project Being Developed in Serbia.Las Naciones Unidas. Paz para Kosovo.Aniversario sin fiesta.Population by national or ethnic groups by Census 2002.Article 7. Coat of arms, flag and national anthem.Serbia, flag of.Historia.«Serbia and Montenegro in Pictures»Serbia.Serbia aprueba su nueva Constitución con un apoyo de más del 50%.Serbia. Population.«El nacionalista Nikolic gana las elecciones presidenciales en Serbia»El europeísta Borís Tadic gana la segunda vuelta de las presidenciales serbias.Aleksandar Vucic, de ultranacionalista serbio a fervoroso europeístaKostunica condena la declaración del "falso estado" de Kosovo.Comienza el debate sobre la independencia de Kosovo en el TIJ.La Corte Internacional de Justicia dice que Kosovo no violó el derecho internacional al declarar su independenciaKosovo: Enviado de la ONU advierte tensiones y fragilidad.«Bruselas recomienda negociar la adhesión de Serbia tras el acuerdo sobre Kosovo»Monografía de Serbia.Bez smanjivanja Vojske Srbije.Military statistics Serbia and Montenegro.Šutanovac: Vojni budžet za 2009. godinu 70 milijardi dinara.Serbia-Montenegro shortens obligatory military service to six months.No hay justicia para las víctimas de los bombardeos de la OTAN.Zapatero reitera la negativa de España a reconocer la independencia de Kosovo.Anniversary of the signing of the Stabilisation and Association Agreement.Detenido en Serbia Radovan Karadzic, el criminal de guerra más buscado de Europa."Serbia presentará su candidatura de acceso a la UE antes de fin de año".Serbia solicita la adhesión a la UE.Detenido el exgeneral serbobosnio Ratko Mladic, principal acusado del genocidio en los Balcanes«Lista de todos los Estados Miembros de las Naciones Unidas que son parte o signatarios en los diversos instrumentos de derechos humanos de las Naciones Unidas»versión pdfProtocolo Facultativo de la Convención sobre la Eliminación de todas las Formas de Discriminación contra la MujerConvención contra la tortura y otros tratos o penas crueles, inhumanos o degradantesversión pdfProtocolo Facultativo de la Convención sobre los Derechos de las Personas con DiscapacidadEl ACNUR recibe con beneplácito el envío de tropas de la OTAN a Kosovo y se prepara ante una posible llegada de refugiados a Serbia.Kosovo.- El jefe de la Minuk denuncia que los serbios boicotearon las legislativas por 'presiones'.Bosnia and Herzegovina. Population.Datos básicos de Montenegro, historia y evolución política.Serbia y Montenegro. Indicador: Tasa global de fecundidad (por 1000 habitantes).Serbia y Montenegro. Indicador: Tasa bruta de mortalidad (por 1000 habitantes).Population.Falleció el patriarca de la Iglesia Ortodoxa serbia.Atacan en Kosovo autobuses con peregrinos tras la investidura del patriarca serbio IrinejSerbian in Hungary.Tasas de cambio."Kosovo es de todos sus ciudadanos".Report for Serbia.Country groups by income.GROSS DOMESTIC PRODUCT (GDP) OF THE REPUBLIC OF SERBIA 1997–2007.Economic Trends in the Republic of Serbia 2006.National Accounts Statitics.Саопштења за јавност.GDP per inhabitant varied by one to six across the EU27 Member States.Un pacto de estabilidad para Serbia.Unemployment rate rises in Serbia.Serbia, Belarus agree free trade to woo investors.Serbia, Turkey call investors to Serbia.Success Stories.U.S. Private Investment in Serbia and Montenegro.Positive trend.Banks in Serbia.La Cámara de Comercio acompaña a empresas madrileñas a Serbia y Croacia.Serbia Industries.Energy and mining.Agriculture.Late crops, fruit and grapes output, 2008.Rebranding Serbia: A Hobby Shortly to Become a Full-Time Job.Final data on livestock statistics, 2008.Serbian cell-phone users.U Srbiji sve više računara.Телекомуникације.U Srbiji 27 odsto gradjana koristi Internet.Serbia and Montenegro.Тренд гледаности програма РТС-а у 2008. и 2009.години.Serbian railways.General Terms.El mercado del transporte aéreo en Serbia.Statistics.Vehículos de motor registrados.Planes ambiciosos para el transporte fluvial.Turismo.Turistički promet u Republici Srbiji u periodu januar-novembar 2007. godine.Your Guide to Culture.Novi Sad - city of culture.Nis - european crossroads.Serbia. Properties inscribed on the World Heritage List .Stari Ras and Sopoćani.Studenica Monastery.Medieval Monuments in Kosovo.Gamzigrad-Romuliana, Palace of Galerius.Skiing and snowboarding in Kopaonik.Tara.New7Wonders of Nature Finalists.Pilgrimage of Saint Sava.Exit Festival: Best european festival.Banje u Srbiji.«The Encyclopedia of world history»Culture.Centenario del arte serbio.«Djordje Andrejevic Kun: el único pintor de los brigadistas yugoslavos de la guerra civil española»About the museum.The collections.Miroslav Gospel – Manuscript from 1180.Historicity in the Serbo-Croatian Heroic Epic.Culture and Sport.Conversación con el rector del Seminario San Sava.'Reina Margot' funde drama, historia y gesto con música de Goran Bregovic.Serbia gana Eurovisión y España decepciona de nuevo con un vigésimo puesto.Home.Story.Emir Kusturica.Tercer oro para Paskaljevic.Nikola Tesla Year.Home.Tesla, un genio tomado por loco.Aniversario de la muerte de Nikola Tesla.El Museo Nikola Tesla en Belgrado.El inventor del mundo actual.República de Serbia.University of Belgrade official statistics.University of Novi Sad.University of Kragujevac.University of Nis.Comida. Cocina serbia.Cooking.Montenegro se convertirá en el miembro 204 del movimiento olímpico.España, campeona de Europa de baloncesto.El Partizan de Belgrado se corona campeón por octava vez consecutiva.Serbia se clasifica para el Mundial de 2010 de Sudáfrica.Serbia Name Squad For Northern Ireland And South Korea Tests.Fútbol.- El Partizán de Belgrado se proclama campeón de la Liga serbia.Clasificacion final Mundial de balonmano Croacia 2009.Serbia vence a España y se consagra campeón mundial de waterpolo.Novak Djokovic no convence pero gana en Australia.Gana Ana Ivanovic el Roland Garros.Serena Williams gana el US Open por tercera vez.Biography.Bradt Travel Guide SerbiaThe Encyclopedia of World War IGobierno de SerbiaPortal del Gobierno de SerbiaPresidencia de SerbiaAsamblea Nacional SerbiaMinisterio de Asuntos exteriores de SerbiaBanco Nacional de SerbiaAgencia Serbia para la Promoción de la Inversión y la ExportaciónOficina de Estadísticas de SerbiaCIA. Factbook 2008Organización nacional de turismo de SerbiaDiscover SerbiaConoce SerbiaNoticias de SerbiaSerbiaWorldCat1512028760000 0000 9526 67094054598-2n8519591900570825ge1309191004530741010url17413117006669D055771Serbia