C语言:编写一个程序实现从键盘接收一个字符串,并将这个字符逆序输出

2024-11-08 00:00:09
有1个网友回答
网友(1):

改进一下

用字符数组实现,字符串长度有限制

#include
#include

int main(void)
{
int i;
int ch[128];

for (i = 0; (ch[i] = getchar()) != '\n'; i++);

printf("\n");

for (; i >= 0; i--)
printf("%c", ch[i]);

getch();
return 0;
}

在 TC 上测试通过

用链表实现,动态存储,字符串长度无限制

#include
#include
#include
#include
#define TYPE struct ch
#define LEN sizeof(struct ch)

int main(void)
{
TYPE
{
char c;
TYPE *previous;
TYPE *next;
};
TYPE *head, *last;
TYPE *p, *q;

head = (TYPE *)malloc(LEN);
p = head;
q = NULL;

printf("Input a string : ");

if ((head->c = getch()) != '\r')
do
{ if (p->c != '\b')
{
printf("%c", p->c);
p->previous = q;
q = p;
p->next = (TYPE *)malloc(LEN);
p = p->next;
}
else
{ if (q != NULL)
{ free(p);
p = q;
q = p->previous;
printf("\b \b");
}
}
}
while((p->c = getch()) != '\r');

p->previous = q;
p->next = NULL;
last = p;

printf("\n\nThe string inputed is : ");
q = last->previous;

while (q != NULL)
{ printf("%c", q->c);
q = q->previous;
}

getch();
return 0;
}
在 TC 上测试通过