scanf 활용에 대해
보통 공개 웹서버를 보면 쿼리 파싱 부분에 sscanf 를 많이 쓰게 됩니다.
까먹고 있다가.. 오늘 관련 문서를 보아서 글을 남겨 봅니다..
혹시 다른 좋은 팁이 있으시면 같이 리플 남겨 주세요.
--------------------------------------------------------------------
Using sscanf to Extract Strings
Consider the problem of taking a string of the form;
a MyArr[Bill]=/turtle/
and extracting the name "Bill" and the nickname "turtle.
Consider the following code (which works). The numbers are not really part of the code. Rather, they are references in the discussion.
#include <stdio.h>
main()
{
char line[80], s1[80], s2[80], s3[80], s4[80], s5[80], s6[80];
strcpy(line, "a MyArr[Bill]=/turtle/");
sscanf(line, "%s %[^\[]%[\[]%[a-z,A-Z]%[\]=/]%[^/]",
1 2 3 4 5 6
s1, s2, s3, s4, s5, s6);
}
1. It is clear that s1 will be "a". The form of the format specifer is the familiar space.
2. The [^...] indicates the string can contain any character up to the character or characters specified at the dots. In this case, the specified character is '['. However as [ has special meaning, it is indicated as '\['. Thus, in this case MyArr is written to string s2.
3. The [...] indicates the string can contain only the characters at the dots. In this case the specified character is ']'. As it is a special character, it is specified as '\['. Thus, '[' is written to s3.
4. The [a-z,A-Z] indicates the string can only contain these alphabetical characters. Thus "Bill" is written to s4.
5. The [\]=/] indicates that the string can only contain the characters ']', '=' and '/'. Thus, "]=/" is written to s5.
6. The [^/] indicates the string can contain any character other than '/'. Thus, "turtle" is written to string s6.
------------------------------------
댓글 달기