繁体   English   中英

printf()仅在我的while循环中打印空值

[英]printf() is only printing null values during my while loop

谁能解释为什么在尝试打印字符串值时会得到以下读数:(null)(null)(null)?

这是我的代码:

char
translate(char *fileName2)
    {
   char *str1;
   int counted;
   int count;
   int printed;
   int i;
   FILE * fp;
   i = 0;
   count = 0;
   counted = 0;
   printed = 0;
   fp = fopen(fileName2, "r");
   do
    {
       if (!feof(fp)&&counted==0)
         {
              count+=1;
              readToken(fp);
         }
      else
         {
             counted=1;
         } 
    }
    while (counted==0);
     printf("there are %d words in the file %s\n",count,fileName2);
     do 
     {
    if (i<count)
         {
            //Problem here
            printed=0;
            i+=1;
            str1 = readToken(fp); 
            printf("%s ",str1); //THIS IS WHERE THE NULL GETS PRINTED!!
            //free(str1);
         }
      else
         {
            printed=1;
            printf("file has been printed\n");
            printf("value of count here is:%d\n",count);
            printf("value of i here is:%d\n",i);
         } 
      }
     while(counted==1&&printed==0);
   fclose(fp);
   return(0);
    }

我只是真的不明白为什么当我尝试打印它时为什么给我(空)str1的值。 可能有更好的方法来执行此操作,但是我不是最高级的,因此任何建议都将不胜感激...谢谢:)

编辑:这是readToken()的代码

char *
readToken(FILE *fp)
{
int ch,index;
char *buffer;
int size = 80;

skipWhiteSpace(fp);

ch = fgetc(fp);
if (ch == EOF) return 0;

buffer = allocateMsg(size,"readToken");

index = 0;
while (!isspace(ch))
    {
    if (ch == EOF) break;
    if (index > size - 2)
        {
        ++size;
        buffer = reallocateMsg(buffer,size,"readToken");
        }
    buffer[index] = ch;
    ++index;
    ch = fgetc(fp);
    }

/* push back the character that got us out of this loop */

ungetc(ch,fp);
buffer[index] = '\0';

return buffer;
}

您可能要添加

  rewind(fp);   //you need to reset the file pointer to the beginning. 

在第二个while循环之前:

     do 
    {
      if (i<count)
      {
        //Problem here
        printed=0;
        i+=1;
        str1 = readToken(fp); 
        printf("%s ",str1); //THIS IS WHERE THE NULL GETS PRINTED!!
        //free(str1);
      }
      else
      {
        printed=1;
        printf("file has been printed\n");
        printf("value of count here is:%d\n",count);
        printf("value of i here is:%d\n",i);
      } 
   }
   while(counted==1&&printed==0);

暂无
暂无

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

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