sscanf的用法示例

 sscanf
Read formatted data from a string.
int sscanf( const char *buffer, const char *format [, argument ] ... );
 
Return Value
Each of these functions returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end of the string is reached before the first conversion.
Parameters
buffer
Stored data
format
Format-control string
argument
Optional arguments
Remarks
The sscanf function reads data from buffer into the location given by each argument. Every argument must be a pointer to a variable with a type that corresponds to a type specifier in format. The format argument controls the interpretation of the input fields and has the same form and function as the format argument for the scanf function.
 
/* SSCANF.C: This program uses sscanf to read data items
* from a string named tokenstring, then displays them.
*/

#include <stdio.h>

void main( void )
{
   char  tokenstring[] = "15 12 14...";
   char  s[81];
   char  c;
   int   i;
   float fp;

   /* Input various data from tokenstring: */
   sscanf( tokenstring, "%s", s );
   sscanf( tokenstring, "%c", &c );
   sscanf( tokenstring, "%d", &i );
   sscanf( tokenstring, "%f", &fp );

   /* Output the data read */
   printf( "String    = %s\n", s );
   printf( "Character = %c\n", c );
   printf( "Integer:  = %d\n", i );
   printf( "Real:     = %f\n", fp );
}

Output
String    = 15
Character = 1
Integer:  = 15
Real:     = 15.000000
 
下面是我從其他文章中摘錄的幾個例子:
  1. 常見用法。
  char str[512] = {0};
  sscanf("123456 ", "%s", str);
  printf("str=%s\n", str);
  2. 取指定長度的字符串。如在下例中,取最大長度爲4字節的字符串。
  sscanf("123456 ", "%4s", str);
  printf("str=%s\n", str);
  3. 取到指定字符爲止的字符串。如在下例中,取遇到空格爲止字符串。
  sscanf("123456 abcdedf", "%[^ ]", str);
  printf("str=%s\n", str);
  4. 取僅包含指定字符集的字符串。如在下例中,取僅包含1到9和小寫字母的字符串。
  sscanf("123456abcdedfBCDEF", "%[1-9a-z]", str);
  printf("str=%s\n", str);
  5. 取到指定字符集爲止的字符串。如在下例中,取遇到大寫字母爲止的字符串。
  sscanf("123456abcdedfBCDEF", "%[^A-Z]", str);
  printf("str=%s\n", str);
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章