0
Someone could help me, I want you to concatenate the first 2 characters of each of these 3 strings, I attach my program
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char cadena1[20] ,cadena2[20], cadena3[20]; printf("Introduce la primer cadena 1>"); scanf("%s",cadena1); printf("Introduce la segunda cadena 2>"); scanf("%s",cadena2); printf("Introduce la tercera cadena 3> "); scanf("%s",cadena3); printf("\nCadenas concatenadas -> %s\n",strcat(cadena1,cadena2,)==0); printf("\ncontenido de cadena1:"); puts (cadena1); printf("\ncontenido de cadena2:"); puts (cadena2); printf("\nCadenas concatenadas -> %s\n",strcat(cadena1,cadena3)==0); printf("\ncontenido de cadena1:"); puts (cadena1); printf("\ncontenido de cadena3:"); puts (cadena3); return 0; }
3 Respuestas
+ 1
You can use 2D char array as <cadenas> and use loop to read input, copy characters.
#include <stdio.h>
#include <string.h>
#define INPUTS 3 // number of string
#define COPIES 2 // number of char to be copied
int main()
{
const char *legend[INPUTS] = { "primer", "segunda", "tercera" };
char cadenas[INPUTS][20], res[7] = { 0 };
for (size_t i = 0; i < INPUTS; i++)
{
printf("Introduce la %s cadena %lu > ", legend[i], i + 1);
fflush(stdout);
scanf("%s", cadenas[i]);
puts(cadenas[i]); // for Code Playground
strncat(res, cadenas[i], COPIES);
}
puts(res); // result
return 0;
}
+ 2
Thanks a lot
+ 1
I think you don't need strcat() for that. Just:
char result[] = {cadena1[0], cadena1[1], cadena2[0], cadena2[1], cadena3[0], cadena3[1], '\0'};
puts(result);