Here is a quick and dirty working example of how this could be done.
However, it is not very safe/foolproof. E.g., you can easily overrun the animal
buffer with scanf()
. Also, if you change the format of the string in sprintf()
, you'll need to make sure str
has enough room.
#include <stdio.h>
int main()
{
char animal[20];
char str[29];
animal[19] = 0; /* make sure animal is 0-terminated. Well, scanf() will 0-term it in this case anyway, but this technique is useful in many other cases. */
printf("Name the beast (up to 19 characters): ");
scanf("%s", animal);
sprintf( str, "Is it a %s?", animal );
puts(str);
return 0;
}
And here is a somewhat improved version. We make sure that we don't read more characters than the animal
buffer can hold, define a pre-processor macro for the maximum animal name length for easier maintenance, trap the case when the user entered more characters than asked, get rid of the newline that terminates user input.
#include <stdio.h>
#include <string.h>
#define MAX_ANIMAL_NAME_LEN 9
int main()
{
/* 1 char for 0-terminator + 1 to catch when a user enters too
many characters. */
char animal[MAX_ANIMAL_NAME_LEN + 2];
char str[MAX_ANIMAL_NAME_LEN + 11];
printf("Name the beast (up to %d characters): ", MAX_ANIMAL_NAME_LEN);
fgets( animal, MAX_ANIMAL_NAME_LEN + 2, stdin );
{
/* fgets() may include a newline char, so we get rid of it. */
char * nl_ptr = strchr( animal, '\n' );
if (nl_ptr) *nl_ptr = 0;
}
if (strlen(animal) > MAX_ANIMAL_NAME_LEN)
{
fprintf( stderr, "The name you entered is too long, "
"chopping to %d characters.\n", MAX_ANIMAL_NAME_LEN );
animal[MAX_ANIMAL_NAME_LEN] = 0;
}
sprintf( str, "Is it a %s?", animal );
puts(str);
return 0;
}
As other users have pointed out, strings in C, as the C language itself, can get fairly tricky pretty fast. Further improvements will be your homework. Search engines are your friends. Happy learning!
One treacherous pitfall you may want to beware is that there is still input to be read from STDIN if the user has typed more than fgets() wanted to accept. If you call fgets() or some other input function later on, you will read those extra characters, which is probably not what you wanted! Please see the following posts:
How to clear input buffer in C?
C: Clearing STDIN
Thanks to chux for pointing this out.