Skip to the content.

C语言sscanf和sprintf的用法及实例

2013-04-16 11:08:16


近来编程要用到这两个函数,这里结合MSDN以及自己的使用,对这两个函数作一下简要说明,加深对这两个函数的理解!

sscanf:

int sscanf( const char *buffer, const char *format [, argument ] ... );
Example
/* 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

sprintf:

int sprintf( char *buffer, const char *format [, argument] ... );
Example
/* SPRINTF.C: This program uses sprintf to format various
* data and place them in the string named buffer.
 */

#include <stdio.h>
void main( void )
{
char  buffer[200], s[] = “computer”, c = ‘l’;
int   i = 35, j;
float fp = 1.7320534f;

/* Format and print various data: */
j  = sprintf( buffer,     “\tString:    %s\n”, s );
j += sprintf( buffer + j, “\tCharacter: %c\n”, c );
   j += sprintf( buffer + j, “\tInteger:   %d\n”, i );
   j += sprintf( buffer + j, “\tReal:      %f\n”, fp );

printf( “Output:\n%s\ncharacter count = %d\n”, buffer, j );
}

Output
Output:
String:    computer
Character: l
   Integer:   35
   Real:      1.732053

character count = 71

以下就是我编程时候用到的,希望对看到的朋友有帮助:

#include <stdio.h>
#include <stdlib.h>
void main( void )
{
	char buffer[1024];
	int i, ch;
	
	//getchar
	printf( "Enter a line: " );
	for( i = 0; (i < 1024) &&  ((ch = getchar()) != EOF) 
		&& (ch != '\n'); i++ )
		buffer[i] = (char)ch;

	buffer[i] = '\0';
	//printf( "%s\n", buffer );

	char* username = (char*)malloc(30);
	char* password = (char*)malloc(32);

	//sscanf
	sscanf( buffer, "netdisk -u%s -p%s", username, password );

	printf( "username = %s\n", username );
	printf( "password = %s\n", password );

	//sprintf
	char* sql = (char*)malloc(1024);
	sprintf(sql, "select * from `user` where `username` = '%s'", username);

	printf( "sql = %s\n", sql );
}