用C解析文本 [英] Parsing text in C

查看:167
本文介绍了用C解析文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的文件:

...
words 13
more words 21
even more words 4
...

(一般格式是不一串数字,然后是一个空格,然后任意数量的数字和换行符)

(General format is a string of non-digits, then a space, then any number of digits and a newline)

和我想要解析的每一行,把文字变成结构的一个领域,而进入其他的数量。眼下虽然字符不是数字,然后读取剩下的我使用的读线的丑陋的黑客。我相信有一个更清晰的方式。

and I'd like to parse every line, putting the words into one field of the structure, and the number into the other. Right now I am using an ugly hack of reading the line while the chars are not numbers, then reading the rest. I believe there's a clearer way.

推荐答案

编辑:您可以使用PNUM-BUF得到串的字母部分的长度,并使用函数strncpy()到复制到另一个缓冲区。一定要一个'\\ 0'添加到目标缓冲区的末尾。我会在PNUM ++之前插入此code。

You can use pNum-buf to get the length of the alphabetical part of the string, and use strncpy() to copy that into another buffer. Be sure to add a '\0' to the end of the destination buffer. I would insert this code before the pNum++.

int len = pNum-buf;
strncpy(newBuf, buf, len-1);
newBuf[len] = '\0';

您可以读取整个行到一个缓冲区,然后用:

You could read the entire line into a buffer and then use:

char *pNum;
if (pNum = strrchr(buf, ' ')) {
  pNum++;
}

要得到一个指针号码字段。

to get a pointer to the number field.

这篇关于用C解析文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆