1) 'string3' is uninitialized, so the first character may not be '\0', which will cause strcat to work improperly.
2) 'fgets' may append a newline. You need to search for it and strip it out, if present.
3) 'strcat', along with any other function that doesn't take the size of the buffer into consideration, is unsafe. Unfortunately, strncat doesn't guarantee a null termination, so it is unsafe as well!
4) Don't use 'magic constants'. Define a standard buffer size, or pass variables.
Suggestion:
Code:
#include<stdio.h>
#include<string.h>
/*
Reads a line from standard input, and discards the newline, if present
*/
char* getline( char* buf, size_t max )
{
char
* nln,
* ret = fgets( buf, max, stdin );
if( ret )
{
nln = strchr( ret, '\n' );
if( nln )
*nln = '\0';
}
return ret;
}
/*
A safe strncat alternative
*/
char* concat( char* buf, const char* end, size_t max )
{
size_t
len = strlen( buf );
char
ch,
* ptr = buf + len;
for( ;; )
{
if( ++len >= max )
break;
ch = *end++;
if( ch == '\0' )
break;
*ptr++ = ch;
}
*ptr = 0;
return buf;
}
/*
Sets the first character in a buffer to '\0'
*/
char* reset( char* buf )
{
*buf = '\0';
return buf;
}
#define MAX_BUF 64
int main()
{
char string[MAX_BUF], string2[MAX_BUF], string3[MAX_BUF];
printf("Please enter your first name.\n");
getline(string, sizeof( string ));
printf("Please enter your last name. \n");
getline(string2, MAX_BUF);
reset( string3 );
concat(string3, string, MAX_BUF);
concat(string3, " ", MAX_BUF);
concat(string3, string2, MAX_BUF);
printf( "Your name is %s. \n", string3);
getchar();
return 0;
}