如果输入字符串中没有空格,我有以下代码。
char* input2 = "(1,2,3)";
sscanf (input2,"(%d,%d,%d)", &r, &n, &p);
以下输入失败:
char input2 = " ( 1 , 2 , 3 ) ";
如何解决这个问题?
答案 0 :(得分: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.