简体   繁体   中英

printf(“%s”) not working properly

So i have this big code ( so wont be able to put the entire thing here). But at a point i have this.

while(ptr1!=NULL)
{
printf("%sab ",ptr1->name);
puts(ptr1->name);
ptr1=ptr1->next;
}

Now my ptr1 point to a an entry of the array of a structure( each entry being a linked list), and the structure was populated from a file.

Now in this loop it prints

FIRSTab FIRST
SECONDab SECOND
THIRD

Now why doesnt my THIRD GETS PRINTED TWICE?

Also if i do

printf(" %s",ptr1->name); // i.e. one space before %s

I get

THIRDD

Putting 2 spaces before %s gives me

THIRDRD

3 spaces gives

THIRDIRD

And so on.

Also if i try to do strcmp(ptr1->name,"THIRD") i wont get the correct comparison for THIRD. Why??

Here is how i populated my structure.

// G is the structure, fp is passed as argument to function.
//THe file format is like this.
//FIRST SECOND THIRD
//NINE ELEVEN 
//FOUR FIVE SIX SEVEN
// and so on.
int i=0,j=0,k=0;
char string[100];
while(!feof(fp))
{
if(fgets(string,100,fp))
{
G[i].index=i;
k=0;j=0;
//\\printf("%d",i);
//puts(string);
node *new=(node*)malloc(sizeof(node));
new->next=NULL;
G[i].ptr=new;
node* pointer;
pointer=G[i].ptr;
while(string[j]!='\n')
{
    if(string[j]==' ')
    {
    pointer->name[k]='\0';

    k=0;
        node *new=(node*)malloc(sizeof(node));
        new->next=NULL;
        pointer->next=new;
        pointer=pointer->next;
        j++;
    }
    else
    {   
    pointer->name[k++]=string[j]; 
    j++; 
    }
}
pointer->name[k]='\0';
i++;
}

Your third string probably contains the characters THIRD followed by \\r (carriage return). Why it contains this can only be determined by knowing the contents of the file and how your read it.

It is likely that you are either working on a system that uses a single newline character as a line terminator (but the file you are opening comes from a system that uses a carriage return and newline pair) or that the file pointer that you were passed ( fp ) was opened in binary mode.

If you can't change the file pointer to be opened in text mode then a quick fix might be to change this condition while(string[j]!='\\n') to while(string[j]!='\\n' && string[j] != '\\r') , although you might want a more robust solution that handles multiple whitespace characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM