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"
- save first character ("letter") - char c = pig[0];
- move rest of - pig1- charbeginning- 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.) 
- replace "old" last character "old", stored first character - pig[strlen(pig) - 1] = c;
- append - "ay"- strcat(pig, "ay");
- 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.
- initialise - pig- 0s- char pig[100] = "";
- scan in data - scanf("%98s", pig); /* add tests failure reading needed. */
- append first character of input, copy end of - pig- pig[strlen(pig)] = pig[0];
- move of - pig1 character beginning- memmove(pig, pig + 1, strlen(pig) - 1);
- print result: - printf("%s\n", pig);
Comments
Post a Comment