如何使用C中的strtok从char数组中的文本文件中显示3行

时间:2017-05-06 00:08:19

标签: c file lines strtok display

我有一份作业,我无法真正找到代码问题所在。主要问题是从文本文件中读取3行并使用它们来构建二叉树。文本文件包含以下行:

7
2 4 0 0 7 0 0
3 5 6 0 0 0 0


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
  const char* p;
  const char* v1;
  const char* v2;
  char buf[100];
  FILE *fptr = fopen("sd.in", "r");
  if (fptr == NULL) {
    printf("Failed to open file\n");
    return -1;
  }
  if(fgets(buf,100,fptr)!=NULL)
    p=strtok(buf,"\n");
  printf("%s\n", p);
  while((p = strtok(NULL,"\n"))!=NULL)
  {  
    printf("%s\n", p);
  }        

  fclose(fptr);
  return 0;
}

到目前为止,这是我的代码。当我编译它时,它只显示第7行的第7行。我怎么能显示所有的行?非常感谢你!

更新 代码。现在我可以显示第一行和第二行但没有数字2.我想在v1中存储第二行,在v2中存储第三行。

        if(fgets(buf,100,fptr)!=NULL)
         p=strtok(buf,"\n");
         printf("%s\n", p);
       if((p = strtok(buf,"\n"))!=NULL && fgets(buf,100,fptr)!=NULL)
       v1 = strtok(NULL,"\n");
       printf("%s\n ",v1);

1 个答案:

答案 0 :(得分:-1)

这是工作代码。 由于缓冲区的内存地址不是常量,因此无法对v1和v2使用char指针。它们需要存储到标题中提到的数组中,但是您的描述说明了另一个。需要跳过只有换行符的行。

#include <stdio.h>
#include <string.h>
int
main(void)
{
   FILE *fp;
   char caBuffer[50];
   char caV1[50], caV2[50], caCnt[2];
   const char *cp;
   const char *cpDelimeter = "\n";
   int iLoopCnt = 0;

   if( ( fp = fopen( "xyz.txt", "r" ) ) == NULL ){
      printf( "failed opening\n" );
      return 1;
   }

   while( fgets( caBuffer, sizeof(caBuffer), fp ) != NULL ){
      //skip the lines with newline char
      if( strlen(caBuffer) > 1 )
      {  
         cp = strtok(caBuffer, cpDelimeter);

         if( cp != NULL ){
            switch( iLoopCnt++ )
           {
              case 0:
                  strcpy(caCnt, cp );
                  break;
              case 1:
                  strcpy(caV1, cp );
                  break;
              case 2:
                  strcpy(caV2, cp );
                  break;
            }
        }
    }
}

printf("caCnt = %s\n", caCnt );
printf("caV1  = %s\n", caV1 );
printf("caV2  = %s\n", caV2 );

fclose(fp);

return 0;

}

根据以下建议进行了更新。 感谢。