【发布时间】:2012-10-17 21:11:25
【问题描述】:
我需要的是:
1) 像 sscanf 一样从字符串中读取
2) 像 sscanf 一样用 "%n" 测量处理序列的长度
3) 接受format 和上面的其他参数(无法控制)
有什么办法吗?
size_t read = 0; //Accumulator of the length of processed characters
void readfn (char* source_string, char* fmt, va_list args)
{
int length;
size_t fmtlen = strlen(fmt);
char* fmt_and_lenght = (char*)realloc(fmt, fmtlen + 3);
fmt_and_length[fmtlen] = '%';
fmt_and_length[fmtlen + 1] = 'n';
fmt_and_length[fmtlen + 2] = '\0';
va_list args_and_length = va_append(args, length); //here is the problem, i need to add &length to the list (i dont care if the list is created from scretch
vsscanf(source_str, fmt_and_length, args_and_length); //here i finally capture the length of processed string
read += length; //and i do whatever i wanted to do with it
}
即使 fmt 不包含 "%n" 并且参数列表之前没有捕获它,它也会简单地计算消耗的字符数?
编辑:如果有 vsnscanf 或者它应该有什么名字肯定会更好,这将得到处理的字符数。但是我通过将格式字符串拆分为未转义的 % 来解决这个问题。如果它后面没有*,我会获取一个参数并迭代地处理所有参数,每次我添加“%n”并在最后总结长度。
【问题讨论】:
-
不知道你在这里问什么,你能改写清楚一点吗?
-
我编辑了这个问题,所以我希望它更清楚