scanf() - C語言庫函數

C庫函數 int scanf(const char *format, ...)  讀取從標準輸入格式的輸入。 

聲明

以下是聲明scanf()函數的功能。

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

參數

  • format -- 這是C的字串,其中包含以下各項中的一個或多個:

    空白字元,非空白字元和格式說明。格式說明符如: [=%[*][width][modifiers]type=] 詳細說明如下:

參數 描述
* 這是一個可選的星號表示該數據是從流中被讀取的,但忽略,即,它不會存儲在相應的參數。
width 這指定在當前讀出操作被讀取的最大字符數
modifiers Specifies a size different from int (in the case of d, i and n), unsigned int (in the case of o, u and x) or float (in the case of e, f and g) for the data zaixianed by the corresponding additional argument: h : short int (for d, i and n), or unsigned short int (for o, u and x) l : long int (for d, i and n), or unsigned long int (for o, u and x), or double (for e, f and g) L : long double (for e, f and g)
type 的字元,指定將要讀取的數據的類型以及它是如何被讀取。請參閱下表。

fscanf類型說明:

類型 合格輸入 參數類型
c 單字符:讀取下一個字元。如果不同寬度從1被指定,函數讀取字元寬度,並將它們存儲在連續位置的數組作為參數傳遞。沒有空字元在末尾追加。 char *
d 十進位整數:號碼任意前面有+或 - 號 int *
e,E,f,g,G 浮點十進位數的小數點,可選擇前面+或 - 號,可以選擇後跟e或E字元和一個十進位數。兩個有效條目的示例是-732.103和7.12e4 float *
o 八進制整數 int *
s 一串字元。這將讀取後續字元,直到找到一個空格(空格字元被認為是空白,換行符和標籤)。 char *
u 無符號整數。 unsigned int *
x,X 十六進制整數 int *
  • additional arguments -- 根據格式字串,函數可能會想到一系列的額外的參數,每個包含一個值,而不是插入的格式參數中指定的標記每個%標籤,如果有的話。應該有相同數量的%預期值的標籤的數量的這些參數的。

返回值

如果成功,寫入的字元的總數被返回,否則返回一個負數。

例子

下麵的例子演示了如何使用 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
", str1);
   printf("Entered Website:%s", str2);

   return(0);
}

讓我們編譯和運行上面的程式,這將在交互模式下產生以下結果:

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

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

上一篇: fscanf() - C語言庫函數 下一篇: sscanf() - C語言庫函數