C/C++ Practice Questions on User Input Problem 9

This is my series on C/C++ problems for accepting user input in a robust way. The questions of this series start from C programs, and they slowly build and convert to classes, and which further build into inheritance. This is Problem 9 of this series.

Last Reviewed and Updated on February 7, 2020
Posted by Parveen(Hoven),
Aptitude Trainer and Software Developer

User Input - Problem 9

Write a C++ class based on _cgets that asks the user to enter a string of characters with a limit of 10 characters, ie, the user should be asked to enter not more than 10 characters. If he violates this limit, only the first ten should be accepted and displayed.

Solution
// include all the headers
#include "conio.h"
#include <iostream>

class CConsoleInput
{

private:
    // the maximum limit allowed, use a static const
    // initialize here itself
    static const int iMAXCHARS = 10;

    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
    CConsoleInput ()
    {

        // requirement for _cgets
        m_cBuff [0] = (iMAXCHARS + 2) + 1;

    }

    // destructor
    ~CConsoleInput ()
    {

        // 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]);

    }

public:
    void ReadConsoleString ()
    {

        m_cReturn = NULL;

        int iLoopCtr = 0;

        printf ("Enter a string [<= %u characters]: ", iMAXCHARS);

        m_cReturn = _cgets (m_cReturn);

        // save length in a variable. Why are we saving it ?
        m_iInputLength = strlen (m_cBuff);

    }

    void DisplayString ()
    {

        std::cout << "The string is: " <<

        this->m_cReturn << std::endl;

        if (m_iInputLength > iMAXCHARS)
        {

            std::cout << "NOTE: truncated to "
            << iMAXCHARS << " chars";

            std::cout << std::endl;

        }

    }

};

int main ()
{

    CConsoleInput obj;

    obj.ReadConsoleString ();

    obj.DisplayString ();

    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.



Creative Commons License
This Blog Post/Article "C/C++ Practice Questions on User Input Problem 9" 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