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);
 

你可能感兴趣的:(职场,示例,用法,休闲,sscanf)