I have a string that looks like this: {opt,2}{home,4}...
I have to scan opt and 2 into a string and integer. I am doing this:
我有一个看起来像这样的字符串:{opt,2} {home,4} ...我必须将opt和2扫描成一个字符串和整数。我这样做:
char str[40] = "{opt,2}{home,4}";
char s[20];
int *x;
sscanf(str, "{%[^,],%[0-9]}", s,&x);
This segfaults. What is the right way?
这段错误。什么是正确的方法?
1 个解决方案
#1
2
To scan text like that, you don't need regex, you could just use simple scanf
specifiers.
要扫描这样的文本,你不需要正则表达式,你可以使用简单的scanf说明符。
char s[16]; /* The string in the pair */
int n; /* The integer in the pair */
int len; /* The length of the pair */
for (; sscanf(buf, "{%[^,],%d}%n", s, &n, &len) == 2; buf += len) {
/* use str and n */
}
The %n
specifier simply receives the number of characters read in the sscanf
call, and stores it in the matching argument (in this case, len
). We use this value so that we can increment the buf
that is being read from, so that the next string-int pair may be read.
%n说明符只接收在sscanf调用中读取的字符数,并将其存储在匹配参数中(在本例中为len)。我们使用这个值,以便我们可以增加正在读取的buf,以便可以读取下一个string-int对。
#1
2
To scan text like that, you don't need regex, you could just use simple scanf
specifiers.
要扫描这样的文本,你不需要正则表达式,你可以使用简单的scanf说明符。
char s[16]; /* The string in the pair */
int n; /* The integer in the pair */
int len; /* The length of the pair */
for (; sscanf(buf, "{%[^,],%d}%n", s, &n, &len) == 2; buf += len) {
/* use str and n */
}
The %n
specifier simply receives the number of characters read in the sscanf
call, and stores it in the matching argument (in this case, len
). We use this value so that we can increment the buf
that is being read from, so that the next string-int pair may be read.
%n说明符只接收在sscanf调用中读取的字符数,并将其存储在匹配参数中(在本例中为len)。我们使用这个值,以便我们可以增加正在读取的buf,以便可以读取下一个string-int对。