C 庫 - sscanf() 函式



C 庫 sscanf(const char *str, const char *format, ...) 函式從字串中讀取格式化的輸入,並將結果儲存到提供的變數中。

語法

以下是 C 庫 sscanf() 函式的語法:

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

引數

此函式接受以下引數:

  • str: 要讀取的輸入字串。
  • format: 指定如何解釋輸入字串的格式字串。
  • ...: 指向將儲存提取值的變數的其他引數。

返回值

該函式返回成功匹配和賦值的輸入項數。如果輸入與格式字串不匹配,則函式返回 EOF 或成功匹配和賦值的項數(直至該點)。

格式說明符

以下是格式說明符列表:

  • %d: 讀取整數。
  • %f: 讀取浮點數。
  • %s: 讀取字串。
  • %c: 讀取字元。
  • %x: 讀取十六進位制整數。
  • %o: 讀取八進位制整數。
  • %u: 讀取無符號整數。

示例 1:解析整數和字串

以下程式碼演示了從輸入中解析整數和字串。

以下是 C 庫 sscanf() 函式的示例。

#include <stdio.h>

int main() {
   const char *input = "42 Alice";
   int number;
   char name[20];

   int result = sscanf(input, "%d %s", &number, name);

   printf("Parsed number: %d\n", number);
   printf("Parsed name: %s\n", name);
   printf("Number of items matched: %d\n", result);

   return 0;
}

輸出

以上程式碼產生以下結果:

Parsed number: 42
Parsed name: Alice
Number of items matched: 2

示例 2:解析十六進位制數和字元

此示例從輸入字串中解析十六進位制數和字元。

#include <stdio.h>

int main() {
   const char *input = "0xA5 Z";
   int hexValue;
   char character;

   int result = sscanf(input, "%x %c", &hexValue, &character);

   printf("Parsed hex value: %x\n", hexValue);
   printf("Parsed character: %c\n", character);
   printf("Number of items matched: %d\n", result);

   return 0;
}

輸出

執行以上程式碼後,我們將得到以下結果:

Parsed hex value: a5
Parsed character: Z
Number of items matched: 2
廣告

© . All rights reserved.