[英]Simple C program involving arrays cannot execute
我有一个家庭作业问题,需要我将用户输入的单词转换为 Pig Latin,方法是将单词的第一个字母移到末尾并添加一个 ay。 例如,星期二变为 uesdayTay。 应重复此过程,直到用户键入 STOP。
我对数组真的很陌生,所以我可能会错误地使用它们,但我找不到原因。 我写的程序可以编译,但是每次执行都会崩溃。 我确信这个程序相当简单,但这是我的代码:
#include <stdio.h>
#include <string.h>
int main ()
{
char *input_word [100], *temp [100], *stop [4];
int n = 0;
printf("Enter a word: ");
for( n = 0; n < 100; n++)
{
scanf("%s", input_word[n]);
}
while ( strcmp ( stop [4], "STOP" ) != 0 )
{
*temp = input_word [0];
for ( int j = 1; j <= n-1; j++)
{
*input_word [j-1] = *input_word [j];
}
input_word [n-1] = *temp;
printf("%s", *input_word);
printf("ay\n");
printf("Type STOP to terminate: ");
for ( n = 0; n < 4; n++ )
{
scanf("%s", stop[n] );
}
}
return 0;
}
任何人都可以帮我吗? 我发现数组相当混乱。 谢谢!
scanf("%s", input_word[n])
我会在那里阻止你。
您将 input_word 声明为一个指针数组,但这些指针是 1. 未初始化 2. 未指向您需要分配的有效内存。
相反,首先声明一个数组来保存来自用户的输入
char input_word[100];
现在为了简单起见,使用 fgets 从命令行读取
fgets(input_word, sizeof(input_word), stdin);
现在删除尾随 \\n(如果有):
char* p = strchr(input_word, '\n');
if (p)
{
*p = '\0';
}
现在您在 input_word 中有“Tuesday\\0”(如果您输入了该词)。
为新单词创建另一个数组:
char output_word[100] = { '\0' };
跳过第一个字符并复制到字符串末尾:
strcpy(output_word, input_word + 1);
现在取第一个字符并添加它:
strncat(output_word, input_word, 1);
然后使用 strcat 添加其余部分,并在代码中添加诸如输入字符串长度之类的检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.