0

How would I add a string to a string that I get from scanf?

Do this:

char animal[size];
scanf("%s", animal);

Then add "Is it a animal?" to whatever is input, then return the whole thing as animal again.

For example if I input 'duck' for animal, it will make animal return "Is it a duck?"

Also, should I add the ? to animal first then add "Is it a "?

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
sa044512
  • 35
  • 1
  • 2
  • 6
  • 3
    Have a look at [`snprintf`](http://linux.die.net/man/3/snprintf) as one option (e.g. `snprintf(second_buf, sizeof(second_buf), "Is it a %s?", animal)`). Probably easier if you used two buffers rather than trying to do it in place with one buffer. Or just `printf` if you want to output straight to the terminal. – kaylum Dec 02 '15 at 02:45
  • Think about what you are doing. Are you trying to add to a string, or print out a string? If you are printing, you can skip adding to the string yourself. Do some research and come back if you need help. – Stewart Smith Dec 02 '15 at 02:47
  • 1
    Possible duplicate of [How to concatenate 2 strings in C?](http://stackoverflow.com/questions/8465006/how-to-concatenate-2-strings-in-c) – dietbacon Dec 02 '15 at 02:53
  • 2
    Funny how people come down hard on anyone using `gets`; but the equally-awful `scanf("%s"` gets nary a mention – M.M Dec 02 '15 at 02:57
  • 2
    I don't mean rude. I think by reading any full C book, you will find the answer yourself. In stackovwrflow, we always want to know what effort you put before asking a question. – texasbruce Dec 02 '15 at 03:13
  • 2
    @sa044512 Actually -- it *isn't* a simple question, not really. Strings in C are never simple -- there are questions about space allocation, buffer size, etc., which are involved even in fairly basic things. The way that you are using `scanf` without worrying if your buffer is big enough is a good example of how easy it is to go astray. In a language like Python you can become a decent programmer by online tutorials and trial and error. C isn't like that. It is hard to grasp without wading through a book-length treatment. (I recommend King's "C Programming - A Modern Approach") – John Coleman Dec 02 '15 at 03:25

3 Answers3

2

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.

Community
  • 1
  • 1
Anatoli P
  • 4,401
  • 1
  • 13
  • 21
  • 1
    Since you know it is not very safe, maybe post an answer that is safe. – chux - Reinstate Monica Dec 02 '15 at 03:20
  • I applaud your extra effort. Yet unclear on how `if (strlen(animal) > MAX_ANIMAL_NAME_LEN)` would ever be true when an input contains `'\n'`. Do not think that is possible. – chux - Reinstate Monica Dec 02 '15 at 05:42
  • The newline will be read into `animal` only if the user enters no more than MAX_ANIMAL_NAME_LEN characters before hitting Enter. Otherwise it won't fit in, and `strlen(animal) > MAX_ANIMAL_NAME_LEN` will be true, so we'll trim `animal` to MAX_ANIMAL_NAME_LEN. – Anatoli P Dec 03 '15 at 02:26
  • Yes I now see the how this would work. Note that there may exist more than 1 excess character for the next input function - if one were ever called. – chux - Reinstate Monica Dec 03 '15 at 03:52
  • Good catch! Thank you. Added a note on that. – Anatoli P Dec 04 '15 at 01:07
0

If you just want to display the message of "Is it a ___?" you can just output it like

char animal[size];
scanf("%s", animal);
printf("Is it a %s?", animal);
Jorgel
  • 851
  • 2
  • 13
  • 23
  • he doesn't want to print it. he wants to return the concatenated string in the function. – dietbacon Dec 02 '15 at 02:54
  • 2
    @dietbacon I don't think it's very clear what the OP wants, since he is asking to return a value from a char array. – Paul Rooney Dec 02 '15 at 03:10
  • @dietbacon: And if he returns the (pointer to) the local variable `animal`, then the code will have other problems — undefined behaviour. Either the space to hold the string needs to be passed to the function, along with the length (probably the best solution), or the space needs to be allocated via `malloc()` in the function (which is probably beyond what the OP can handle right now — in another few weeks, maybe, but not right now). – Jonathan Leffler Dec 02 '15 at 03:20
0

How would I add a string to a string that I get from a scanf?

Adding two different strings,.

#include <stdio.h>
#include <string.h>
int main(void)    
{
    char animal[20], text1[20] = "Is it a ";
    scanf("%11s", animal);
    strcat(text1, animal);
    printf("%s\n", text1);
    return 0;
}
Dilip Kumar
  • 1,711
  • 10
  • 22