如何使用scanf跳过括号

时间:2012-09-20 10:59:11

标签: c

感谢您的帮助......但仍然无法在屏幕上打印出300,400。下面是我的完整代码:读取一个文件[文件包含:S(300,400)]在commandprompt传递并读取其中包含的两个值而不打印或读取S,第一个括号,逗号或最后一个右括号

#include <stdio.h>
int a;
int b;
int main ( int argc, char *argv[] )
{

    if ( argc != 2 ) /* argc should be 2 for correct execution */
    {
        /* We print argv[0] assuming it is the program name */
        printf( "usage: %s filename", argv[0] );
    }
    else 
    {
        // We assume argv[1] is a filename to open
        FILE *file = fopen( argv[1], "r" );

        /* fopen returns 0, the NULL pointer, on failure */
        if ( file == 0 )
        {
            printf( "Could not open file\n" );
        }
        else 
        {
           /*reading file..
             while (fscanf(file, "S(%d,%d)", &a, &b) == 2)
            {
               printf("%d,%d", a, b);
            }


            fclose( file );
        }
    }
}

3 个答案:

答案 0 :(得分:4)

你做得太复杂了。只需在字面上包含非数字部分:

while(fscanf(file, "S(%d,%d)", &a, &b) == 2)
  printf("got S(%d,%d)\n", a, b);

另外,请注意printf()不支持模式,这没有多大意义。

答案 1 :(得分:2)

不需要扫描集,只需使用:

while (2 == fscanf(file, "S(%d,%d)", &a, &b))
{
    printf("%d %d", a, b);
}

2fscanf()的返回值进行比较,因为发布的代码只能读取一个整数(仅fscanf()填充a并返回1)但错误地同时使用ab

答案 2 :(得分:0)

我建议使用实用程序来解析和检查正则表达式。这是一个在线:http://www.regextester.com/

还有很多其他人......

相关问题