我想在每次出现在文本中时将"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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
enter text here
cat
cat
?m?? $$???p??$???Z? ??$??M??v????????????????????? ????????????!??d@8 $
?
???????????5_Segmentation fault
Run Code Online (Sandbox Code Playgroud)
这里几个问题.
未初始化的局部变量.
int i = 0; // loop counter
int size = 0; // size of array
你正在检查a和t尚未阅读的字符.
因此检查t当前输入的字符是否匹配,然后检查a以及c
之前输入的字符,如下所示.
if(i>=2 && input[i-2]=='c' && input[i-1]=='a' && input[i]=='t') // switching characters
{
input[i]='g'; input[i-1]='o'; input[i-2]='d';
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |