So here in this post I am just trying to implement a function capable to read a string of length 'n' from STDIN without memory corruption and other bugs.
Do help me by checking the code if there is a chance for further improvements.
#include <stdio.h>
#include <string.h>
#define BUF_SIZE 6
#define STRING_SIZE 4
/*
* void getStringStdin(char *, int , int );
*
* 1: BUF :Pointer to the array of characters where input string
is to be stored.
* 2: BUF_LEN :Is the length of the array of characters where the
string is stored.buffer where we save the string.
* 3: STRING_LEN :Is the length of the string.
*
* NOTE: STRING_LEN < BUF_LEN
*
*/
getStringStdin(char *buf, int buf_len, int str_len)
{
int ch, len;
char *s;
if(str_len>=buf_len)
len=buf_len-1;
else
len=str_len;
printf ("\nEnter string of length %d(Remaining is ignored): ",len);
if( (fgets(buf, len+1, stdin)) != NULL )
{
s=my_strchr(buf,'\n');
if(s!=NULL)
{
*s='\0';
}
else
{
while ((ch = getchar()) != '\n' && ch != EOF);
}
}
}
int main(void)
{
int i=0;
char buf[BUF_SIZE];
do
{
getString(buf, BUF_SIZE, STRING_SIZE);
printf ("\nString : %s\n", buf);
i++;
}while(i<2);
return 0;
}