There are few things that could have been done better in your code:
- The code does not check how many characters were read. Was a line too short?
- It is not clear why the return of
strncpy
is being checked for NULL
. It does not return NULL
.
- It is not clear whether you initialize
line
and lenght
and to what values.
- Unfortunately, it is hard to be a psychic and guess what is
replaceletter
, what it does, and how tab
and ch
are declared.
- It is a mystery as for why
strncpy
is called in a while
loop.
- It seems like your program does not account for a newline character being a part of the returned string.
In other words, if you want to get more or less adequate help, it is always a good idea to provide a small, complete and working example demonstrating your problem.
If I were assigned that task, I'd probably write it like this:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(void)
{
int ret = EXIT_SUCCESS;
char *line = NULL;
size_t linecap = 0;
ssize_t len;
do {
len = getline(&line, &linecap, stdin);
if (len == -1) {
if (errno != 0) {
perror("readline");
ret = EXIT_FAILURE;
}
break;
}
if (len < 4)
continue; /* Line is too short, try again */
/* printf("The line is: %s", line); */
printf("First three letters are: '%.*s'\n", 3, line);
} while(1);
free(line); /* It is always a good idea to cleanup after yourself */
return ret;
}
I hope that the above snippet is self-explanatory. But if there is something that needs clarification then please don't hesitate to ask.
Good Luck!