I've written a function that requires the user to enter a string of size 13, 15, or 16. The function keeps looping till the required length is entered. I am new to C. This function is part of one of the problem in havard CS50 online course. Though the function works, the logic is hard to follow. Can anyone please help me improve the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *getString() // Returns pointer to a string. Input must be string with length 13, 15 or 16.
{
short lengthOne = 13, lengthTwo = 15, maxLength = 16;
char *str = (char *)malloc(sizeof(char) * maxLength + 1);
do
{
printf("Enter a %d, %d, or %d-char string: ", lengthOne, lengthTwo, maxLength);
fgets(str, maxLength + 2, stdin);
for (int i = 0; i < strlen(str); i++)
{
if (str[i] == '\n')
str[i] = '\0';
}
if (strlen(str) > maxLength)
{
while (getchar() != '\n')
;
}
} while (strlen(str) != maxLength && strlen(str) != lengthOne && strlen(str) != lengthTwo);
return str;
}
int main()
{
char *string = getString();
printf("Content of string: %s\n", string);
printf("Length of string is: %lu\n", strlen(string));
return 0;
}