Concatenate text with variable char in printf

3

I need to concatenate the person's name (variable) with a text. Following logic, it would look like this

#include <stdio.h>

int main (void){
    char nome[6];
    printf("Ola! Insira seu nome, por fovor: \n");
    scanf("%c", &nome);
    printf("Seja bem vindo, \n", nome);
    return 0;
}

But it's not right. I need this in the simplest way possible.

    
asked by anonymous 10.04.2016 / 02:03

2 answers

6

There are 3 problems in the code:

  • The format for string in scanf() is %s (best to use a character quantity limiter you can enter)
  • Since the array is already a reference to an object just pass the variable, it can not get the address of something that is already an address
  • printf() is without the placeholder to accommodate the name
  • Then it would look like this:

    #include <stdio.h>
    
    int main (void) {
        char nome[6];
        printf("Ola! Insira seu nome, por fovor: \n");
        scanf("%5s", nome);
        printf("Seja bem vindo, %s\n", nome);
        return 0;
    }
    

    See working on ideone .

    Formatting documentation for printf() .

        
    10.04.2016 / 02:23
    0

    There are several methods for concatenating strings in C, you can use sprinf , or strcat .

    The sprintf , works equal to printf , the difference is the parameter referring to the string that you will enter the value.

      

    You can concatenate numbers and floating points using sscanf .

    strcat:

    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char **argv){
        char str1[50];
        char str2[50];
        char cat[100];
    
        strcpy(str1,"texto da string1"); // insere o texto em str
        strcpy(str2," | nova parte do texto");
    
        bzero(cat, 100); // limpa a variavel cat
    
        strcat(cat, str1); // concatena valores em cat
        strcat(cat, str2);
    
        puts(cat);
    }
    

    sprintf:

    #include <stdio.h>
    
    int main(int argc, char **argv){
        char str1[50];
        char str2[50];
        char cat[100];
    
        sprintf(str1,"Primeira parte");
        sprintf(str2,"Segunda parte");
        sprintf(cat,"%s - %s",str1, str2);
    
        puts(cat);
    }
    
        
    10.04.2016 / 04:47