C-standard-library-c-function-scanf

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

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

説明

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

宣言

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

int scanf(const char *format, ...)

パラメーター

  • フォーマット-これは、次の項目の1つ以上を含むC文字列です- + ホワイトスペース文字、非ホワイトスペース文字、フォーマット指定子。 以下に説明するように、書式指定子は* [=%[*] [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 *
  • 追加の引数-形式文字列に応じて、関数は追加の引数のシーケンスを期待する場合があり、各引数にはformatパラメーターで指定された各%タグ(存在する場合)の代わりに1つの値が挿入されます。 これらの引数の数は、値を予期する%タグの数と同じでなければなりません。

戻り値

成功すると、関数は、正常に読み取られた引数リストのアイテム数を返します。 読み取りエラーが発生した場合、または読み取り中にファイルの終わりに達した場合、適切なインジケータ(feofまたはferror)が設定され、データが正常に読み取れる前にどちらかが発生した場合、EOFが返されます。

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

#include <stdio.h>

int main () {
   char str1[20], str2[30];

   printf("Enter name: ");
   scanf("%s", str1);

   printf("Enter your website name: ");
   scanf("%s", str2);

   printf("Entered Name: %s\n", str1);
   printf("Entered Website:%s", str2);

   return(0);
}

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

Enter name: admin
Enter your website name: www.finddevguides.com

Entered Name: admin
Entered Website: www.finddevguides.com