一 sscanf和sprintf
如下:
//sscanf
#include <stdio.h>
void main()
{
int a,b;
char str[20] = "12.34";
int input = sscanf(str,"%2d.%2d",&a,&b);
printf("input=%d,a=%d,b=%d\n",input,a,b);
printf("%s\n",str);
}
结果为
input=2,a=12,b=34
12.34
//sprintf
#include <stdio.h>
#include <stdlib.h>
void main()
{
int a,b;
a = 20,b = 30;
char str[20];
int input = sprintf(str,"%d%d",&a,&b);
printf("str=%s\n",str);
printf("input=%d,a=%d,b=%d\n",input,a,b);
}
结果为
str=12450521245048
input=2,a=20,b=30
二 fscanf和fprintf
如下:
//fscanf
#include <stdio.h>
#include <stdlib.h>
void main()
{
int a,b;
FILE *fpInput;
if((fpInput = fopen("input.txt","r")) == NULL)
{
printf("file read fail !\n ");
exit(1);
}
//file input.txt
//==>2312 4523 6756 98 90
int input = fscanf(fpInput,"%d%d",&a,&b);
printf("input=%d,a=%d,b=%d\n",input,a,b);
}
结果为
input=2,a=2312,b=4523
//fprintf
#include <stdio.h>
#include <stdlib.h>
void main()
{
int a,b;
FILE *fpInput;
if((fpInput = fopen("input.txt","w")) == NULL)
{
printf("file read fail !\n ");
exit(1);
}
a = 20,b = 30;
int input = fprintf(fpInput,"%d%d",&a,&b);
printf("input=%d,a=%d,b=%d\n",input,a,b);
}
结果为
//input.txt文件的内容为:12450521245048
input=2,a=20,b=30