Pages

Saturday, 29 May 2021

Chapter 20 // Exercise 5 - Principles & Practice Using C++

In this exercise I am using Visual Studio 2019 and a modified version of the std_lib_facilities header found here.

Chapter 20 // Exercise 5

Define an input and output operator (<< and >>) for vector.


At first I was confused as to whether he meant std::vector or the vector we created. I decided to go with std::vector. We basically did this in Drill 14 of Chapter 19 by reading in { val, val, val } into vectors.

That seems like an odd way to type data in. So I decided on an input loop that just asks for data until you enter ctrl+z to break the loop. The main problem with this is that I have no idea how to allow reading a string with whitespace but also reading in other types. It kind of seems impossible but I'm not experienced enough to say for sure. At this point, I just ignored whitespace to bypass this problem but input and output operators for any type is begging for trouble.

EDIT 01/06/2021
After some thinking (and some googling) I realised that there is no graceful way to make a stringstream convert to any type. I was thinking of checking if T was of type std::string but comments rightfully said you should be specialising your functions more and knowing the kind of types it will be using. I eventually used this suggestion and created 2 input overloads; one for integers/characters and another for strings.

I also spent the evening adding google test to my project so I could add some automated unit tests to my project and not have to faff about with input on a console window when testing. You can read about it here:

No comments:

Post a Comment