1.提取字符串中的数据到变量
// crt_sscanf.c
// compile with: /W3
// This program uses sscanf to read data items
// from a string named tokenstring, then displays them.
#include <stdio.h>
int main( void )
{
char tokenstring[] = "15 12 14...";
char s[81];
char c;
int i;
float fp;
// Input various data from tokenstring:
// max 80 character string:
sscanf( tokenstring, "%80s", s ); // C4996
sscanf( tokenstring, "%c", &c ); // C4996
sscanf( tokenstring, "%d", &i ); // C4996
sscanf( tokenstring, "%f", &fp ); // C4996
// Note: sscanf is deprecated; consider using sscanf_s instead
// Output the data read
printf( "String = %s
", s );
printf( "Character = %c
", c );
printf( "Integer: = %d
", i );
printf( "Real: = %f
", fp );
}
结果
String = 15
Character = 1
Integer: = 15
Real: = 15.000000
2.变量进字符串
int xPos = 1;
int yPos = 2;
char str[50];
sprintf(str, "x:%d,y:%d;", xPos, yPos);