【问题标题】:How to parse textfile correctly?如何正确解析文本文件?
【发布时间】:2015-03-10 18:32:37
【问题描述】:

我有一个文本文件,其中包含我编写的程序中的一堆随机数据:

hdfs45 //the hdsf part stays the same everytime, but the number always changes

我正在尝试将这行数据解析为两部分,hdfs 部分和 45 部分(稍后将转换为 int)

我已经尝试过类似的方法:

Char * a, * b;
char str[100];
FILE* ptr;

ptr = fopen("test.txt","r"); // opens sucessfully

while(fgets(str,100,file))
{
    a = strtok(str," \n");
    printf("%s",a); // but this prints the whole string

}

数据将是随机的,因为将分隔符设置为“45”是没有用的。但是第一部分“hdfs”总是相同的,任何帮助将不胜感激。

【问题讨论】:

  • 不清楚你到底想做什么,这是一个非常具体的例子,很难提出通用的方法。
  • 你保证只有一组字符和一组数字吗?如果是这样,那么我建议查看isdigit
  • hdfs 部分永远不会改变,但它后面的数字总是会改变。
  • 如果前缀始终相同,strncmp(str, "hdfs", 4),只是为了确定然后atoi(str + 4)(或对strtol的等效调用。)如果前缀是可变的,您可以使用@ 987654330@找到第一个数字。

标签: c file parsing pointers printing


【解决方案1】:

如果“hdfs”从不改变,那么您可以简单地将前 4 个字符之后的字符转换为数字,即:

int num = atoi(str + 4);
str[4] = '\0';

在您的示例中,num 将等于 45str 将等于 hdfs

【讨论】:

    【解决方案2】:

    你不能使用strtok,因为没有什么要标记的(你不能使用分隔符),试试:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(void)
    {
        char str[100] = "hdfs45";
        char *ptr;
        long num;
    
        ptr = strpbrk(str, "012345679");
        if (ptr) {
            num = strtol(ptr, NULL, 10);
            *ptr = '\0';
            printf("%s -> %ld\n", str, num);
        }
        return 0;
    }
    

    【讨论】:

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