文字列からデータを読み取りたい。文字列は次のようになります。
"123 35 123 0 0 0 817 0 0 0 0"
文字列には不確かな数字とスペースがいくつかあります。3番目の数字を読みたいです。データの読み方は?
を使用しsscanf()
ます。空白をスキップします。
int a, b, c;
if( sscanf(string, "%d %d %d", &a, &b, &c) == 3)
printf("the third number is %d\n", c);
%*
また、最初の2つの番号の割り当てを抑制するために使用することもできます。
int a;
if( sscanf(string, "%*d %*d %d", &a) == 1)
printf("the third number is %d\n", a);
sscanf()
成功した変換(および割り当て)の数を返すことに注意してください。そのため、出力変数の値に依存する前に、戻り値を確認する必要があります。
sscanf
これのためだけに設計されました。具体的には、*
入力を破棄する修飾子です。
const char *input = "...";
int value;
// here we use the '*' modifier to discard the input from our string
sscanf("%*i %*i %i", &value);
// value now magically has the value you need.
sscanf
ただし、欠点もあります。必要に応じて空白を破棄しますが、従来は低速でもあります。可能であれば、strtol
代わりに使用します。これは高速です(フォーマット文字列を解析する必要がないため)。