我已经设置了一个赋值,将文本行存储到链表中的句号,并颠倒它们的顺序,而不打印句号。
到目前为止,我的代码是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char line[50];
struct node *next;
};
int main()
{
//intialise stuff
char l[50];
int i;
struct node *head = NULL, *newNode, *current;
head = (struct node *)calloc(1,sizeof(struct node));
char c;
//read in list reversed
printf("Enter some lines followed by '.':n");
while(c!='.'){
i=0;
do {
c = getchar();
if (c != '.') {
l[i]=c;
i++;
}
else
{break;}
} while (c!='n');
newNode = (struct node *)calloc(1,sizeof(struct node));
for (i=0;i<strlen(l);i++)
newNode->line[i] = l[i];
newNode->next=head;
head = newNode;
}
//print reversed list
current = head;
while (current != NULL) {
for (i=0;i<strlen(current->line);i++)
printf("%c", current->line[i]);
current = current->next;
}
return 0;
}
该代码适用于以下输入:
hello
there
world.
但是当我输入时
1234
4321
7777.
输出具有的奇怪正方形
00
01
在第一个数字上,如果我输入:
ricky
is
cool.
输出为:
cooly
is
ky
ricky
有人能帮我弄清楚是哪部分代码导致了这种情况吗?
用'\0'关闭字符串,否则strlen和pals将无法计算出实际大小。新行"\n"存储在字符串中,但head有一个额外的"。"处理。
const uint SZ = 50;
struct node { struct node * next; char line[SZ]; };
struct node * wnod, * head = 0;
uint idx;
char ch = 'n';
// read in list reversed
printf( "Enter some lines followed by '.':n" );
while( '.' != ch )
{
wnod = ( struct node * ) calloc( 1, sizeof( struct node ) );
wnod->next = head;
for( idx = 0; idx < SZ - 1; ++idx )
{
ch = getchar();
if( ( '.' != ch ) && ( 'n' != ch ) )
{
wnod->line[idx] = ch;
} else {
wnod->line[idx] = ' '; idx = SZ;
}
}
head = wnod;
}
// print linked list
while( head )
{
for( idx = 0; idx < strlen( head->line ); ++idx )
{
printf( "%c", head->line[idx] );
}
printf( "|n" );
wnod = head; head = head->next; free( wnod );
}