Pages

Wednesday, 30 September 2020

Chapter 17 // Exercise 7, 8 - Principles & Practice Using C++

In this exercise I am using Visual Studio 2017 and the std_lib_facilities header provided by Stroustrup.

Chapter 17 // Exercise 7, 8

7. Write a program that reads characters from cin into an array that you allocate on the free store. Read individual characters until an exclamation mark (!) is entered. Do not use a std::string. Do not worry about memory exhaustion.
8. Do exercise 7 again, but this time read into a std::string rather than to memory you put on the free store (string knows how to use the free store for you).

Github: https://github.com/l-paz91/principles-practice/blob/master/Chapter%2017/Exercise%207,%208

There's no need to re-invent the wheel here as cin will do all the hardwork for you, all you need to do is supply it with a maximum stream buffer size. Back in chapter 7, we extensively used cin.get() during the creation of the calculator. cin.get() has quite a few different overloads which you can find here:

I used the c-string version istream& get(char* s,  streamsize n, char delim). This allows you to give cin a custom delimiting character (in our case !) and will read characters in and store them at the given address up to streamsize. Simples.

Technically it's cheating but he did say use cin.

As for 8, getline() also has a version that allows you to specify a delimiting character:

No comments:

Post a Comment