c - Concatenating Strings-changing words into pig latin -


i keep receiving "segmentation fault (core dumped)". how can swap first letter of given word user inputs end of word , add "ay". example: input "code" output "odecay"

#include<stdio.h> #include<string.h> int main() {    char pig[100],p[10],i[100];    int j,length;    printf("what word change pig latin");    scanf("%s",pig);    length=strlen(pig);    strcat(p,pig[0]);     for(j=0;j<length;j++)    {       pig[j]=pig[j+1];    }    strcat(pig,p);    strcat(pig,"ay");    printf("%s",pig);    return 0; } 

how can swap first letter of given word user inputs end of word , add "ay"

  1. save first character ("letter")

    char c = pig[0]; 
  2. move rest of pig 1 char beginning

    memmove(pig, pig + 1, strlen(pig) - 1);  

    alternativly use statement

    memmove(&pig[0], &pig[1], strlen(pig) - 1); 

    (note memcpy() won't work here source , destiantion overlap.)

  3. replace "old" last character "old", stored first character

    pig[strlen(pig) - 1] = c; 
  4. append "ay"

    strcat(pig, "ay"); 
  5. print result:

    printf("%s\n", pig); 

there no need second "string", char-array.


assuming pig large enough, 1 char larger data scanned in user, 1 can ommit use of intermediate character `c, per sketch above.

  1. initialise pig 0s

    char pig[100] = ""; 
  2. scan in data

    scanf("%98s", pig); /* add tests failure reading needed. */ 
  3. append first character of input, copy end of pig

    pig[strlen(pig)] = pig[0]; 
  4. move of pig 1 character beginning

    memmove(pig, pig + 1, strlen(pig) - 1); 
  5. print result:

    printf("%s\n", pig); 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -