getchar in while loop reading multiple lines stdin
Вопрос
I have used this code for reading in a set of lines of input in one go to finally store them in a double dimensional character array. If i encounter a '\n', i increment the row index of the doubledim char array..
I then have to analyze the resulting double dim char array line by line and perform associated functions.
The problem is that the code shows:
'TIME LIMIT EXCEEDED'
#include <stdio.h>
#include <string.h>
#include <malloc.h>
struct Trees
{
int num;
struct Trees *left;
struct Trees *right;
};
typedef struct Trees t;
t *root = NULL;
int main(void)
{
void insert(int,t **);
void print_pre(t *);
void print_post(t *);
char *q;
char a[2] = " ";
char all[100];
char line[30][100];
int yy;
int nn;
int i,l,j,k,s;
i=0;j=0;k=0;s=0;
while ((all[i]=getchar())!=EOF) //where i start getting input data
{ // notice the single dim char array 'all'
//for storing everything
if(all[i] != '\n')
line[j][k++]=all[i++]; //the double dim array 'line'
else
{
i++;
j++;
k=0;
}
}
l=j;
j=0;
while(l>=0)
{
if (strncmp(line[j],"insert",6) == 0)
{
q = strtok(line[j],a);
while(q != NULL)
{
if(strcmp(q,"insert") != 0)
{
yy = atoi(q);
break;
}
}
insert(yy,&root);
}
else if (strncmp(line[j],"print_pre",9) == 0)
{
print_pre(root);
}
else
{
print_post(root);
}
return 0;
j++;
l--;
}
}
void insert(int d, t **n)
{
if (*n == NULL)
{
(*n)=(t*)malloc(sizeof(t));
(*n)->left = NULL;
(*n)->right = NULL;
(*n)->num = d;
}
else if((*n)->num == d)
{
insert(d,&((*n)->left));
}
else if((*n)->num > d)
{
insert(d,&((*n)->left));
}
else
insert(d,&((*n)->right));
}
void print_pre(t *n)
{
if(n!= NULL)
{ printf("ffs");
printf("%d",n->num);
print_pre(n->left);
print_pre(n->right);
}
}
void print_post(t *n)
{
if(n!= NULL)
{
print_post(n->left);
print_post(n->right);
printf("%d",n->num);
}
}
Нет правильного решения
Не связан с StackOverflow