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

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 4 of this series.

Last Reviewed and Updated on June 24, 2017
Posted by Parveen(Hoven),
Aptitude Trainer and Software Developer


User Input - Problem 4

Write a C-program based on _cgets that asks a user to enter a string of characters that has length less than 15. The program should display the number of characters entered. If the user enters more than 15 characters then the output should be 'You entered more than 15 characters'.

// include all the headers
#include "conio.h"
#include "string.h"
#include "ctype.h"
// set maxchars = 16
// set maxchars = 16. We are setting it to 16 because the maximum no.
// of charcters that we are to accept is 15. So if a user enters
// more than 15, we can inform accordingly. [If we set it to 15,
// then how will we know that he entered more than 15 ?
// so we have to set it to 16]
#define MAXCHARS    16
main ()

    // set a buffer to hold the user input
    char cBuff [MAXCHARS + 3];

    char* cReturn = NULL;

    cBuff [0] = MAXCHARS + 1;

    printf ("\nEnter a string of characters [<= 15 chars]: ");

    cReturn = _cgets (cBuff);

    if (MAXCHARS == strlen (cReturn))
    printf ("You entered more than 15 characters\n");

    else printf ("You entered %u characters\n", strlen (cReturn));


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 4" by Parveen (Hoven) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Updated on 2017-06-24.