%n
既存のコードに最小限の変更を加えるには、次の機能を使用できますsscanf
。
int chars_read;
r[1] = sscanf(c, "%d%n", &r[0], &chars_read);
chars_read
が文字列の長さより短い場合、すべてsscanf
の文字が消費されていないため、文字列は単一の整数だけで構成されていません。
の Linux ドキュメントは、 scanf
Technical Corrigendum 1で導入された追加の例が標準と矛盾していることを指摘していますが、それまでの間、標準は矛盾を解決するために更新されました。sscanf
遭遇する可能性のある実装の不確実な動作に直面して、結果を解釈する方法を次に示します。
switch (r[1]) {
case EOF: // empty string
break;
case 0: // doesn't start with numeric characters
break;
case 1: // starts with number; sscanf follows standards
case 2: // starts with number; sscanf follows TC1
if (c[chars_read] == '\0')
r[1] = 1; // we read entire string
else
r[1] = 0; // didn't read entire string; pretend we read nothing
break;
default: // shouldn't happen
assert(FALSE);
}