Prahlad Yeri Prahlad Yeri - 3 months ago 26
C Question

C string concatenation not working

I'm absolutely new to C language, so please bear with me. The purpose of below program is to take a string input from user, split it on "-" character, then concatenate the first character of all individual parts. For example:

Rivest-Shamir-Adleman


should return:

RSA


The code works perfectly upto the splitting part. The
input
variable stores the user input,
result
is a char pointer to store the actual concatenated result, and I use the
strtok()
function to actually split the string. But the following concatenation part isn't working:

*result++ = token[0];


The
result
variable should print
RSA
in above example, but its just printing
-
. What am I doing wrong?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
char *input;
char *result;
input = malloc(256); //don't read more than 255 chars.
result = malloc(50); //don't read more than 50 chars.
scanf("%s", input);
printf("You entered %s\n", input);
printf("Length is: %u\n", strlen(input));
char *token = strtok(input,"-");
while(token) {
printf("%c\n", token[0]);
*result++ = token[0];
token= strtok(NULL, "-");
}
*result++ = '\0';
printf("result: %s\n",result);
return 0;
}

Answer Source

This works fine. Its just that you preserve the start of the result string. result = temp;Output the same in answer.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) 
{
    char *input;
    char *result, *temp;
    input = malloc(256); //don't read more than 255 chars.
    temp = malloc(50); //don't read more than 50 chars.
    result = temp;
    scanf("%s", input);
    printf("You entered %s\n", input);
    printf("Length is: %u\n", strlen(input));
    char *token = strtok(input,"-");
    while(token) {
        printf("%c\n", token[0]);
        *temp++ = token[0];
        token= strtok(NULL, "-");
    }
    *temp++ = '\0';
    printf("result: %s\n",result);
    return 0;
}