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 "?

6
  • 3
    Have a look at 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. Commented Dec 2, 2015 at 2:45
  • 1
    Possible duplicate of How to concatenate 2 strings in C? Commented Dec 2, 2015 at 2:53
  • 2
    Funny how people come down hard on anyone using gets; but the equally-awful scanf("%s" gets nary a mention Commented Dec 2, 2015 at 2: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. Commented Dec 2, 2015 at 3: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") Commented Dec 2, 2015 at 3:25

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Since you know it is not very safe, maybe post an answer that is safe.
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.
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.
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.
Good catch! Thank you. Added a note on that.
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);

3 Comments

he doesn't want to print it. he wants to return the concatenated string in the function.
@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.
@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).
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.