使用奇数标记解析c-string

时间:2012-10-01 23:14:53

标签: c parsing

我正在尝试解析像

这样的行
1            {2}           {2,3}         {4}

分为4个不同的字符数组

其中1为'1','\ 0'

和括号中的其他数字各占一个 '2'

'2', '3'

'4'

我试过strtok与困境“\ t}”并且我也尝试过sscanf将%s传递给第一列,将“{%S}”传递给其余列。两者都没有给我预期的结果。任何人都可以给我一个正确的方向吗?

1 个答案:

答案 0 :(得分:1)

你的问题是%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