【问题标题】:Tokenize from a textfile reading into an array in C从文本文件中标记化到 C 中的数组中
【发布时间】:2009-12-01 10:40:38
【问题描述】:

从 C 中读取文件时如何进行标记化?

文本文件:

PES 2009;科乐美;DVD 3;500.25; 6

刺客信条;育碧;DVD;598.25; 3

地狱;EA;DVD 2;650.25; 7

char *tokenPtr;

fileT = fopen("DATA2.txt", "r"); /* this will not work */
  tokenPtr = strtok(fileT, ";");
  while(tokenPtr != NULL ) {
  printf("%s\n", tokenPtr);
  tokenPtr = strtok(NULL, ";");
}

想要打印出来:

PES 2009

科乐美

.

.

.

【问题讨论】:

    标签: c text file tokenize


    【解决方案1】:

    试试这个:

    
    main()
    {
        FILE *f;
        char s1[200],*p;
        f = fopen("yourfile.txt", "r");
        while (fgets(s1, 200, f))
        {
    
    
    while (fgets(s1, 200, f))
    {
    
        p=strtok(s1, ";\n");
    
        do
        {
            printf ("%s\n",p);
        }
        while(p=strtok(NULL,";\n"));
    }
    

    }

    200 字符大小当然只是一个例子

    【讨论】:

    • 这也会考虑每行末尾的换行符并正确处理它
    【解决方案2】:

    您必须将文件内容读入缓冲区,例如逐行使用fgets 或类似的。然后使用strtok 对缓冲区进行标记;阅读下一行,重复直到 EOF。

    【讨论】:

      【解决方案3】:

      strtok() 接受 char *const char * 作为参数。您正在传递 FILE *const char *(隐式转换后)。

      您需要从文件中读取一个字符串并将该字符串传递给函数。

      伪代码:

      fopen();
      while (fgets()) {
          strtok();
          /* Your program does not need to tokenize any further,
           * but you could now begin another loop */
          //do {
              process_token();
          //} while (strtok(NULL, ...) != NULL);
      }
      

      【讨论】:

        【解决方案4】:

        使用 strtok 是一个 BUG。试试 strpbrk(3)/strsep(3) 或 strspn(3)/strcspn(3)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多