【问题标题】:parsing a c-string with odd tokens解析带有奇数标记的 c 字符串
【发布时间】:2012-10-01 23:14:53
【问题描述】:

我正在尝试解析这样的一行

1            {2}           {2,3}         {4}

分成4个不同的字符数组

其中 1 是 '1','\0'

和括号中的其他数字分别是 '2'

'2','3'

'4'

我已经尝试了带有困境的 strtok “\t}”,并且我还尝试了 sscanf 将 %s 传递给第一列,将“{%S}”传递给其余列。两者都没有给我预期的结果。谁能给我一个正确的方向?

【问题讨论】:

  • 这可能是正则表达式的工作......
  • 所有数组之间是否有一个空字符?
  • @Kwariz nope 制表符和空格也是第一个“名称”列可以长于一个字符

标签: c parsing


【解决方案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

【讨论】:

  • 我尝试按照您的建议单独解析,但缓冲区似乎没有前进。如果有区别,我使用的是 sscanf 而不是 fscanf。那么会发生什么,我仍然通过 if 语句,但是下一个 sscan 给我 1\t 而不是行首而不是下一组数字。
  • 必须结合这个解决方案才能使用 sscanf 但它可以工作,谢谢stackoverflow.com/a/10827039/384306
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 2022-01-15
  • 2016-01-19
  • 1970-01-01
  • 2023-03-25
  • 2021-10-01
  • 1970-01-01
  • 2013-03-22
相关资源
最近更新 更多