sscanf格式的C++输入

sscanf formatted input in C++

本文关键字:输入 C++ 格式 sscanf      更新时间:2023-10-16

我有下面的代码,如果输入字符串中没有空格,它就可以工作。

char* input2 = "(1,2,3)";
sscanf (input2,"(%d,%d,%d)", &r, &n, &p);

以下输入失败:

char input2 = " ( 1 , 2 , 3  ) ";

如何解决此问题?

简单修复:在模式中添加空格。

char* input2 = "( 1 , 2 , 3 )";
sscanf (input2,"( %d, %d, %d )", &r, &n, &p);

模式中的空格会消耗任意数量的空格,所以您没有问题。测试程序:

        const char* pat="( %d , %d , %d )";
        int a, b, c;
        std::cout << sscanf("(1,2,3)", pat, &a, &b, &c) << std::endl;
        std::cout << sscanf("( 1 , 2 , 3 )", pat, &a, &b, &c) << std::endl;
        std::cout << sscanf("(1, 2 ,3)", pat, &a, &b, &c) << std::endl;
        std::cout << sscanf("(  1 , 2 ,   3 )", pat, &a, &b, &c) << std::endl;

输出:

3
3
3
3

这种行为是因为手册中的以下段落:

A directive is one of the following:
·      A sequence of white-space characters (space, tab, newline, etc.;
       see isspace(3)). This directive matches any amount of white space,
       including none, in the input.