【发布时间】:2018-10-30 08:28:09
【问题描述】:
每次出现在文本中时,我都想将“cat”这个词切换为“dog”。 我不能使用字符串或字符串函数。
我的代码:
#include <stdio.h>
int main()
{
int i; // loop counter
int size; // size of arry
int input[20];
printf("enter text here\n");
while((input[i] = getchar()) != '\n') // input text to the arry
{
if(input[i]=='c' && input[i+1]=='a' && input[i+2]=='t') // switching characters
{
input[i]='d'; input[i+1]='o'; input[i+2]='g';
}
i++;
size++;
}
i=0; // reset for next loop
while(i <= size) // printing the text out ofthe arry
{
putchar(input[i]);
i++;
}
printf("\n");
return 0;
}
输出:
enter text here
cat
cat
ȵm�� $$ŵ��p��$���Zտ ��$��M��v��������������������� ������������!��d@8 $
�
�����������5_Segmentation fault
【问题讨论】:
-
您正在使用未初始化的变量。打开编译器警告!
-
您在第二次循环之前将
i重置为零,但您一开始就没有设置它。你应该初始化i。您还试图展望未来:您针对input[i + 1]和input[i + 2]进行测试——您尚未读取的值。 -
@danglingpointer 但它不工作。