say something like this:
#include <stdio.h>
void main() {
char fname[30];
char lname[30];
printf("Type first name:\n");
scanf("%s", fname);
printf("Type last name:\n");
scanf("%s", lname);
printf("Your name is: %s %s\n", fname, lname);
}
if i type "asdas asdasdasd"
for fname
, it won't ask me to input something for lname
anymore. I just want to ask how i could fix this, thank you.
Putting %s
in a format list makes scanf()
to read characters until a whitespace is found. Your input string contains a space so the first scanf()
reads asdas
only. Also scanf()
is considered to be dangerous (think what will happen if you input more then 30 characters), that is why as indicated by others 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 still not complete. You still should check if fgets()
has encountered some errors. Read more on fgets()
here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With