简体   繁体   English

printf(“%s”)无法正常工作

[英]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. 现在我的ptr1指向一个结构数组的条目(每个条目是一个链表),并从文件中填充结构。

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 在%s之前放置2个空格给了我

THIRDRD

3 spaces gives 3个空格给出

THIRDIRD

And so on. 等等。

Also if i try to do strcmp(ptr1->name,"THIRD") i wont get the correct comparison for THIRD. 另外,如果我尝试做strcmp(ptr1-> name,“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). 你的第三个字符串可能包含字符THIRD后跟\\r (回车)。 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. 您可能正在使用一个使用单个换行符作为行终止符的系统(但是您打开的文件来自使用回车符和换行符对的系统)或者您传递的文件指针( fp )以二进制模式打开。

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. 如果您无法将文件指针更改为在文本模式下打开,则快速修复可能是将while(string[j]!='\\n')更改为while(string[j]!='\\n' && string[j] != '\\r') ,尽管您可能需要一个更强大的解决方案来处理多个空白字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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