2012-02-21 7 views
3

入力文字列に空白がない場合に機能する次のコードがあります。sscanfはC++で書式設定された入力

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

これは、次の入力のために失敗します。

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

この問題を解決するにはどのように?

+0

3 3 3 3 

この現象は、マニュアルから次の段落でありますあなたがそれをスキップする必要がある場合はどこにスペースを入れてスペースを飛ばしたいと思いますが –

答えて

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; 

出力:すべてのscanf関数があれば、入力終端文字としてスペースを扱います

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

+0

試しましたか? – hochl

関連する問題