fgets()
includes the newline at the end of the string (assuming the input has not been truncated), so you need to trim off the trailing newline. There's several ways to do that, here's two:
fgets(name, sizeof(name), stdin);
size_t len = strlen(name);
if(name[len] == '\n')
name[len] = '\0';
char *ptr = strchr(name, '\n');
if(ptr != NULL)
*ptr = '\0';
You should be aware that
fgets()
does not flush the input buffer, so if the user enters "Arnold Schwarzenegger" (length 21 chars), you'l end up with
name = "Arnold Schwarzenegg";
job="er"
. To get around this you could use
getline()
size_t len = 0;
char *input = NULL;
ssize_t rlen;
rlen = getline(&input, &len, stdin);
if(rlen > sizeof(name) {
input[sizeof(name)-1] = '\0';
else if(rlen > 0) {
input[rlen-1] = '\0';
else {
}
strcpy(name, input);
free(buff);
When using
getline()
the second parameter,
len
in the above example, is the size of the input buffer that has been allocated by
getline()
. You don't need to free and reset the input buffer between calls to
getline()
. The second parameter to getline is the size of the allocated input buffer, so if you need to read several lines you only need to call
free()
after your last use of the input buffer. This also means that
getline()
will only reallocate the buffer as it needs to.