2012-02-21 119 views
3

我有下面的代码,如果输入字符串中没有空格,它的工作原理。sscanf格式化输入C++

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

这失败以下输入:

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

如何解决这一问题?

+0

所有的scanf函数将把空间为输入终止字符,如果你想跳过空间,然后把空间放在任何你需要跳过它 – 2012-02-21 07:38:57

回答

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. 
+0

谢谢,但这个失败的“(1,2,3)” – Avinash 2012-02-21 07:48:10

+0

你试过吗? – hochl 2012-02-21 07:54:03