Concatenate char variable text in printf

Asked

Viewed 10,981 times

5

I need to concatenate the name of the person (variable) with a text. Following the 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 it in the simplest way possible.

  • A simple way to concatenate Char into C++ https://youtu.be/ZkYhmHD7XRo

2 answers

9


There are 3 problems in the code:

  1. the format for string in the scanf() is %s (better use a limiter of the amount of characters you can enter)
  2. like the array is already a reference for an object just pass the variable, can not pick up the address of something that is already an address
  3. the 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Documentation of the formatting of printf().

  • Not quite correct. If the user enters more than 5 characters, the input buffer nome[] will be overflowed. Resulting in Undefined behaviour and can lead to a seg fault Event. Suggest:scanf("%5s", nome);

  • 1

    I’m better, but if I’m gonna do it right, I might as well not scanf().

2

There are several methods to concatenate strings into C, you can use the sprinf, or the strcat.

The sprintf, works the same as printf, the difference is the string parameter that you will insert the value of.

You can concatenate numbers and floating points using the 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.