我如何解析出使用sscanf的同时支持空字段以逗号分隔字符串的领域? [英] How do I parse out the fields in a comma separated string using sscanf while supporting empty fields?

查看:1021
本文介绍了我如何解析出使用sscanf的同时支持空字段以逗号分隔字符串的领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个逗号分隔的字符串,其中可能包含空字段。例如:

I have a comma separated string which might contain empty fields. For example:

1,2,,4

使用基本

sscanf(string,"%[^,],%[^,],%[^,],%[^,],%[^,]", &val1, &val2, &val3, &val4);

我从开始的空场前的空场中的所有值,和意想不到的结果。

I get all the values prior to the empty field, and unexpected results from the empty field onwards.

当我从sscanf的删除前pression空字段()

When I remove the expression for the empty field from the sscanf(),

sscanf(string,"%[^,],%[^,],,%[^,],%[^,]", &val1, &val2, &val3, &val4);

一切工作顺利。

由于我不知道什么时候我会得到一个空场呢,有没有办法改写前pression处理空字段优雅?

Since I don't know when I'm going to get an empty field, is there a way to rewrite the expression to handle empty fields elegantly?

推荐答案

如果您使用 strtok的使用逗号作为分隔符,你会得到字符串一个列表或更多的将是零/零长度。

If you use strtok with the comma as your separator character you'll get a list of strings one or more of which will be null/zero length.

有一个在我的<一个href=\"http://stackoverflow.com/questions/1483206/how-to-tokenize-string-to-array-of-int-in-c/1483218#1483218\">answer这里以获取更多信息。

Have a look at my answer here for more information.

这篇关于我如何解析出使用sscanf的同时支持空字段以逗号分隔字符串的领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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