我有一个文本文件,其中包含我编写的程序中的一堆随机数据:
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”始终是相同的,任何帮助将不胜感激。
最佳答案
如果“hdfs”永远不会改变,那么您只需将前4个后面的字符转换为数字即可,即:
int num = atoi(str + 4);
str[4] = '\0';
在您的示例中,num
将等于 45
,str
将等于 hdfs
。
关于c - 如何正确解析文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28971474/