使用 sscanf 读取字符串的其余部分 [英] reading the remainder of a string with sscanf
问题描述
我正在尝试读取一个字符串,该字符串由一组数字后跟一个字符串组成,其中包含一些其他基本文本.
I'm trying to read a string which consists of a set of numbers followed by a string, wrapped with some other basic text.
换句话说,行的格式是这样的:
In other words, the format of the line is something like this:
Stuff<5,10,-5,8,"Test string here.">
天真地,我试过了:
sscanf(str,"Stuff<%d,%d,%d,%d,\"%s\">",&i1,&i2,&i3,&i4,str2);
但经过一些研究,我发现 %s
应该在遇到空白字符时停止解析.我找到了这个问题,但没有一个答案能解决我的问题have:字符串中可以包含任何字符,包括换行符和正确转义的引号.后者不是问题,如果我可以让 sscanf 将所有内容放在我提供的预分配缓冲区中的第一个引号之后,我可以自己去掉结尾.
But after some research I discovered %s
is supposed to stop parsing when it gets to a whitespace character. I found this question, but none of the answers addresses the problem I have: the string could contain any character in it, including newline characters and properly escaped quotes. The latter is not a problem, if I can just get sscanf to put everything after the first quote in the pre-allocated buffer I provide, I can strip the end off myself.
但是我该怎么做呢?我不能使用 %[]
因为它需要一些东西来终止字符串,而我唯一想终止它的是空终止符.所以我想,嘿,我就用空终止符吧!"但是 %[\0]
使编译器脾气暴躁:
But how do I do this? I can't use %[]
because it requires something in it to terminate the string, and the only thing I want to terminate it is the null terminator. So I thought, "Hey, I'll just use the null terminator!" But %[\0]
made the compiler grumpy:
warning: no closing ‘]’ for ‘%[’ format
warning: embedded ‘\0’ in format
warning: no closing ‘]’ for ‘%[’ format
warning: embedded ‘\0’ in format
使用诸如 %*c
之类的东西也行不通,因为我不知道到底需要取多少个字符.我尝试传递 strlen(str)
因为它会小于那个,但是 sscanf
返回 4 并且什么都没有放入 str2
,这表明也许因为长度太长它放弃了,没有打扰.
Using something like %*c
won't work either, because I don't know exactly how many characters need to be taken. I tried passing strlen(str)
since it will be less than that, but sscanf
returns 4 and nothing is put into str2
, suggesting that perhaps because the length was too long it gave up and didn't bother.
更新:我想我可以这样做:
Update: I guess I could do something like:
sscanf(str,"Stuff<%d,%d,%d,%d,\"%n",&i1,&i2,&i3,&i4,&n);
str2 = str+n;
推荐答案
您的更新似乎是一个不错的答案.在使用 sscanf
通过 i1
获取 i1
之后,我打算建议 strchr
找到第一个引号字符的位置i4代码>.旁注,您应该始终检查 sscanf
的返回值以确保转换有效.这对于您建议的答案更为重要,因为如果前四次转换不成功,n
将保持未初始化状态.
Your update seems to be a good answer. I was going to suggest strchr
to find the location of the first quote char, after using sscanf
to get i1
thru i4
. Side note, you should always check the return value from sscanf
to make sure that the conversions worked. This is even more important with your suggested answer, since n
will be left uninitialized if the first four conversions aren't successful.
这篇关于使用 sscanf 读取字符串的其余部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!