我正在尝试解析一行
1 {2} {2,3} {4}
分成4个不同的字符数组
其中 1 是 '1','\0'
括号中的其他数字均为“2”
'2','3'
'4'
我已经尝试了带有困境的 strtok “\t}”,并且我还尝试了 sscanf 将 %s 传递给第一列,将“{%S}”传递给其余列。两者都没有给我预期的结果。谁能给我推动正确的方向?
您的问题是%S
解析以空格结尾的单词(因此它将“}”作为字符串的一部分读取。
fscanf(stream, "{%[^}]}", buffer);
将 '{}' 之间的字符扫描到缓冲区中。
注意:您可能还需要注意这里的缓冲区溢出。
"{%[^}]}"
{ -> Matches {
%[<char>] -> Matches a sequence of characters that match any of the characters in <char>
If the first character is ^ this makes it a negative so any characters that
do not follow the ^
%[^}] -> Matches a sequence of characters that does not match `}`
} -> Matches }
但我会尝试单独解析这些数字。
// If the input does not contain '{' next then we get an error and the
// next section of code is not entered.
if (fscanf(stream, " {") != EOF)
// Note: The leading space matches one or more white space characters
// So it is needed to get passed leading white space.
{
// We enter this section only if we found '{'
int value;
char next;
while(fscanf(stream, "%d%c", &value, &next) == 2)
{
// You have an integer in value
if (next == '}')
{ break;
}
if (next == ',')
{ continue;
}
// You have an error state the next character after the number was not
// a space or a comma ',' or end of section '}'
}
}
使用此代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
while (scanf(" {") != EOF)
{
printf("Enter BLOCK\n");
int value;
char next;
while(scanf("%d%c", &value, &next) == 2)
{
if ((next == '}') || (next == ','))
{
printf("\tVALUE %d\n",value);
}
if (next == '}')
{ break;
}
if (next == ',')
{ continue;
}
printf("ERROR\n");
exit(1);
}
printf("EXIT BLOCK\n");
}
}
然后像这样使用:
> gcc gh.c
> echo " {2} {2,3} {4}" | ./a.out
Enter BLOCK
VALUE 2
EXIT BLOCK
Enter BLOCK
VALUE 2
VALUE 3
EXIT BLOCK
Enter BLOCK
VALUE 4
EXIT BLOCK