c - 如何在 C 中使用 strtok 在字符数组中显示文本文件中的 3 行

标签 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。我怎样才能显示所有行?非常感谢!

更新代码。现在我可以显示第一行和第二行,但没有数字 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);

最佳答案

这是工作代码。 由于缓冲区的内存地址不是恒定的,因此无法对 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;

}

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

关于c - 如何在 C 中使用 strtok 在字符数组中显示文本文件中的 3 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43815313/

相关文章:

java - 如何测试这个程序

java - 创建一个二进制文件

java - BufferedReader 在用 java 读取我的文件时跳过每一行

c - 从 Pthread 返回值

将 SAS 连接到 C 库

c - "FATAL: Module not found error"使用 modprobe

C:编辑二进制文件

file - SIP 调用有任何文件格式吗?

Java OutputStream 到多个文件

regex - Perl 多行匹配,同时从文件中逐行读取