Inserting %s
in the list of formats allows scanf()
to read characters until a space is found. Your input line contains a space, so the first scanf()
reads only asdas
. In addition, scanf()
is considered dangerous (think what happens if you enter more than 30 characters), so as others have indicated, you should use fgets()
.
Here is how you could do it:
#include <stdio.h> #include <string.h> int main() { char fname[30]; char lname[30]; printf("Type first name:\n"); fgets(fname, 30, stdin); /* we should trim newline if there is one */ if (fname[strlen(fname) - 1] == '\n') { fname[strlen(fname) - 1] = '\0'; } printf("Type last name:\n"); fgets(lname, 20, stdin); /* again: we should trim newline if there is one */ if (lname[strlen(lname) - 1] == '\n') { lname[strlen(lname) - 1] = '\0'; } printf("Your name is: %s %s\n", fname, lname); return 0; }
However, this piece of code is not yet complete. You should still check if fgets()
encountered some errors. Read more about fgets()
here .
source share