我一直收到“段错误(核心已转储)”。 如何将用户输入的给定单词的第一个字母交换到单词的末尾,然后添加一个“ay”。 例如: 输入“代码” 输出“衰减”
#include<stdio.h>
#include<string.h>
int main()
{
char pig[100],p[10],i[100];
int j,length;
printf("What word would you like to change into 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 I swap the first letter of a given word that the user inputs to the end of the word and then add an "ay"
保存第一个字符(“字母”)
char c = pig[0];
将剩余的
pig
一个char
移到开头memmove(pig, pig + 1, strlen(pig) - 1);
交替使用这个语句
memmove(&pig[0], &pig[1], strlen(pig) - 1);
(请注意,由于源和目标重叠,memcpy() 在这里不起作用。)
用存储的“旧”第一个字符替换“旧”最后一个字符
pig[strlen(pig) - 1] = c;
附加
"ay"
strcat(pig, "ay");
打印结果:
printf("%s\n", pig);
不需要第二个“字符串”,char
-array。
假设 pig
足够大,即比用户要扫描的数据大一个 char
,甚至可以省略中间字符 ` c,按照我上面的草图。
将
pig
初始化为所有0
char pig[100] = "";
扫描数据
scanf("%98s", pig); /* Add tests for failure reading as needed. */
附加输入的第一个字符,即将其复制到
的末尾pig
pig[strlen(pig)] = pig[0];
将所有
pig
一个字符移到开头memmove(pig, pig + 1, strlen(pig) - 1);
打印结果:
printf("%s\n", pig);
关于Concatenating Strings-changing words into pig latin 拼接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31487252/