You are not logged in.
I'm new to c and I'm having a slight problem.I'm doing an exercise and wrote a simple program, it compiles fine but when i run the program and input my first & last names only my last name and the space are being displayed to the terminal.
// A program that asks two questions, first name & last name then concatenate the strings together
# include <stdio.h>
# include <string.h>
main ()
{
// Define your variables
char fname[43];
char lname[20];
char space[2];
int length;
// This will read in your variables. ( Initializing it )
printf ("Enter your first name: ");
scanf ("%s", fname);
setbuf (stdin, NULL);
// This will read in your variables. ( Initializing it )
printf ("Enter your last name: ");
scanf ("%s", fname);
// Initialize the space variable, concatenate the variables together & find the size of the name.
strcpy (space, " ");
strcat (fname, space);
strcat (fname, lname);
length = strlen (fname);
printf ("\n");
printf ("Your name is %s & the size of your name is %d bytes\n", fname, length);
// This will stop the program from exiting until one byte of data is entered. ( A keystroke )
setbuf (stdin, NULL);
getchar();
}
Last edited by unilx (2011-07-21 02:13:31)
Offline
I don't know anything about C, but I think you have a typo:
printf ("Enter your last name: ");
scanf ("%s", fname);
Shouldn't it be 'lname'?
I've compiled it with this change and it seems to work (although you might want to subtract the space from the count):
[karol@black test]$ ./t1
Enter your first name: karol
Enter your last name: bla
Your name is karol bla & the size of your name is 9 bytes
Last edited by karol (2011-07-21 02:05:34)
Offline
I don't know how i missed that...damn typos.
Thanks for the help.
Offline
Just be careful of buffer overflows. Here is a better input method:
void get_input(char *buffer, int length) {
char *nl;
fgets (buffer, length, stdin);
if ((nl = strchr(buffer, '\n')) != NULL) {
*nl = '\0';
}
}
Offline