C-standard-library-c-function-sscanf

提供:Dev Guides
移動先:案内検索

Cライブラリ関数-sscanf()

説明

Cライブラリ関数 int sscanf(const char str、const char * format、…​)*は、フォーマットされた入力を文字列から読み取ります。

宣言

以下は、sscanf()関数の宣言です。

int sscanf(const char *str, const char *format, ...)

パラメーター

  • str -これは、関数がデータを取得するためのソースとして処理するC文字列です。
  • format -これは、次の項目の1つ以上を含むC文字列です:Whitespace character、Non-whitespace characterおよびFormat specifiers +書式指定子は、このプロトタイプに従います:[=%[*] [width] [modifiers] type =]
Sr.No. Argument & Description
1 これはオプションの開始アスタリスクです。これは、データがストリームから読み取られるが無視されることを示します。 対応する引数には保存されません。
2

width

これは、現在の読み取り操作で読み取られる最大文字数を指定します。

3

modifiers

が指すデータに対して、int(d、i、nの場合)、unsigned int(o、u、xの場合)、またはfloat(e、f、gの場合)とは異なるサイズを指定します対応する追加の引数:h:short int(d、i、nの場合)、またはunsigned short int(o、u、xの場合)l:long int(d、i、nの場合)、またはunsigned long int(oの場合、 uおよびx)、またはdouble(e、fおよびgの場合)L:long double(e、fおよびgの場合)

4

type

読み取られるデータのタイプと、その読み取り方法を指定する文字。 次の表を参照してください。

fscanf型指定子

type Qualifying Input Type of argument
c Single character: Reads the next character. If a width different from 1 is specified, the function reads width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end. char *
d Decimal integer: Number optionally preceded with a + or - sign int*
e, E, f, g, G Floating point: Decimal number containing a decimal point, optionally preceded by a + or - sign and optionally followed by the e or E character and a decimal number. Two examples of valid entries are -732.103 and 7.12e4 float *
o Octal Integer: int*
s String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab). char *
u Unsigned decimal integer. unsigned int*
x, X Hexadecimal Integer int *
  • その他の引数-この関数は、一連のポインタを追加の引数として期待します。各引数は、同じ順序で、フォーマット文字列内の対応する%タグで指定されたタイプのオブジェクトを指します。 +データを取得するフォーマット文字列の各フォーマット指定子には、追加の引数を指定する必要があります。 sscanf操作の結果を通常の変数に保存する場合は、識別子の前に参照演算子を付ける必要があります。 アンパサンド記号(&)。たとえば、int n; sscanf(str、 "%d"、&n);

戻り値

成功すると、関数は入力された変数の数を返します。 データが正常に読み取られる前に入力が失敗した場合、EOFが返されます。

次の例は、sscanf()関数の使用法を示しています。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
   int day, year;
   char weekday[20], month[20], dtm[100];

   strcpy( dtm, "Saturday March 25 1989" );
   sscanf( dtm, "%s %s %d  %d", weekday, month, &day, &year );

   printf("%s %d, %d = %s\n", month, day, year, weekday );

   return(0);
}

次の結果を生成する上記のプログラムをコンパイルして実行しましょう-

March 25, 1989 = Saturday