In this exercise I am using Visual Studio 2017 and the std_lib_facilities header provided by Stroustrup.
Chapter 18 // Exercise 10Look at the "array solution" to the palindrome problem in section 18.7.2. Fix it to deal with long strings by (a) reporting if an input string was too long and (b) allowing an arbitrarily long string. Comment on the complexity of the two versions.
In this one, he didn't say we couldn't use the std library, so I used cin.getline() instead of just the normal cin >>. This allows whitespace to be read as getline() only skips new lines (unless you give it a different delimiting character). Getline() will then continue reading up until the max and append a terminating 0, regardless of whether there were any characters to read.
The next problem was checking if the reading stopped because the buffer ran out of characters or there were too many characters. We can use cin.fail() to check if the stream failed to read. The failbit will be set if it reaches the end of the buffer and still hasn't encountered the delimiting character. A message can then be printed and cin needs to be reset for the next iteration.
I'm not sure if we were supposed to do it a different way as this wasn't entirely complex so I can't comment on the complexity of the two versions.
No comments:
Post a Comment