Question

My file has the following pattern.

word1 word2 word3
wordzz word33 word2431 word341

and so on.

Now i read the whole file in an array of structure, each of the entry of the array maintains the linked list for each line of file.

Now the whole code is kind of difficult to explain, but here is the problem.

In a particular place when i try to do the following

printf("\n%s",ptr1->name);
puts(ptr1->name);

where ptr1 is the ptr to the head of any linked list. (say line 1 )
name field is the name i.e. word1,word2 etc. Now the output is

word1word1
word2word2
word3

Howcome word3 does not get printed twice? This whole problem even prevents me to strcmp the last word of the list.

Kindly help.

P.S.

also when i do

printf("%d",ptr1);

it prints three different values for ptr, none of them being NULL.

I have two similar arrays of the same structure. I use the same function to populate the two arrays. NOW

    node* ptr,*ptr1; 
ptr=first[i].ptr;
ptr1=second[i].ptr;
while(ptr!=NULL) 
{
printf(" \n1");
printf(" %s", ptr->name); // Works Fine
if(!strcmp(ptr->name,"string")) 
    {


    while(ptr1!=NULL)
    {
        printf("A %s ",ptr1->name);// Problem
                    fflush(stdout);  // EDITS AS ASKED BY USER `pmg`
                    puts(ptr1->name);       
                if(!strcmp(ptr1->name,strt))
        {
            printf("\n 4\n");
            return 1;
        }
        else
        {
        ptr1=ptr1->next;
        }
    }
    return 0;


    }
else 
    {
    ptr=ptr->next;
    }

}

Howcome i get problem @ the mentioned place, and not @ the 'works fine' place.

At works fine, i am shown all the nodes ( names ) but at the problem point i am not shown the last name.

But if i do puts at the problem , it displays that name too.

if before this snippet of code i print the second array using printf only. it does print every node (name) . Can someone tell me why is it not printing later.?

Was it helpful?

Solution

printf("\n%s",ptr1->name); // Problem

stdout is line-buffered by default when connected to a terminal, you have to flush the stream to have the string printed. Use fflush(stdout) just after the printf call to flush stdout. Printing a new line character will also flush stdout when the stream is line-buffered.

puts does not need the additional new line character as puts always appends a new line character to the output.

As @JensGustedt mentioned in the question comment, putting the new line before the string is bad habit "think of a line as being terminated by a '\n' and organize your code accordingly."

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top