User Input - Problem 10
Change class in the previous program, i.e., in problem 9, to a base class so that it has all the mechanism to accept up to 10 characters from the console.
Solution/* The base class CConsoleBase holds all the code for reading a string from the console and limit it to 10 characters. We can then derive classes from this class for specialized console input, such as a string class, integer class, double class and so on. In this example we are writing the string class CConsoleString that is derived from CConsoleBase */ // include all the headers #include "conio.h" #include <iostream> class CConsoleBase { public: // the maximum limit allowed, use a static const // initialize here itself static const int iMAXCHARS = 10; protected: char m_cBuff [iMAXCHARS + 3 + /*take two more so that overflow can be detected*/2]; char* m_cReturn; // the length of string entered by the user. // this length is required during cleanup when // we flush the unwanted characters. so we make it // a private member int m_iInputLength; public: // constructor CConsoleBase () { // requirement for _cgets m_cBuff [0] = (iMAXCHARS + 2) + 1; } // destructor ~CConsoleBase () { // cleanup // Robust programming - // remove any unwanted, unread characters from // the stream if (iMAXCHARS == m_iInputLength) _cgets (m_cBuff); do { m_cReturn = _cgets (m_cBuff); }while (0 != m_cReturn [0]); } protected: // returns success if the user enters a string <= 10 chars bool ReadConsoleString () { m_cReturn = NULL; int iLoopCtr = 0; m_cReturn = _cgets (m_cBuff); // save length in a variable. Why are we saving it ? m_iInputLength = strlen (m_cReturn); return (m_iInputLength <= iMAXCHARS); } }; class CConsoleString : public CConsoleBase { public: inline bool TakeStringInput () { return ReadConsoleString (); } inline const char* DisplayStringInput () { return this->m_cReturn; } }; int main () { CConsoleString obj; printf ( "Enter a string [<= %u characters]: ", CConsoleBase::iMAXCHARS); if (obj.TakeStringInput ()) printf ("You entered '%s'\n", obj.DisplayStringInput ()); else printf ("Truncated input is '%s'\n", obj.DisplayStringInput ()); return 0; }
My C/C++ Videos on Youtube
Here is the complete playlist for video lectures and tutorials for the absolute beginners. The language has been kept simple so that anybody can easily understand them. I have avoided complex jargon in these videos.
This Blog Post/Article "C/C++ Practice Questions on User Input Problem 10" by Parveen (Hoven) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Updated on 2020-02-07. Published on: 2015-12-20