Search Suggest

Formatted Input and Output


1. printf, sprintf and fprintf
 #include <stdio.h>  
int printf(const char *format, ...);
int sprintf(char *s, const char *format, ...);
int fprintf(FILE *stream, const char *format, ...);

printf xuất dữ liệu ra stdout.
sprintf ghi dữ liệu vào buffer được trỏ bởi s.
fprintf ghi dữ liệu vào stream.

Ex:
sprintf.c
 /* sprintf example */  
#include <stdio.h>

int main ()
{
char buffer [50];
int n, a=5, b=3;
n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
printf ("[%s] is a string %d chars long\n",buffer,n);
return 0;
}

fprintf.c
 /* fprintf example */  
#include <stdio.h>

int main ()
{
FILE * pFile;
int n;
char name [100];

pFile = fopen ("myfile.txt","w");
for (n=0 ; n<3 ; n++)
{
puts ("please, enter a name: ");
gets (name);
fprintf (pFile, "Name %d [%-10.10s]\n",n+1,name);
}
fclose (pFile);

return 0;
}

2. scanf, fscanf, and sscanf
 #include <stdio.h>  
int scanf(const char *format, ...);
int sscanf(const char *s, const char *format, ...);
int fscanf(FILE *stream, const char *format, ...);

scanf đọc dữ liệu từ stdin và lưu trên format.
sscanf đọc dữ liệu từ buffer s và lưu trên format.
fscanf đọc dữ liệu từ stream và lưu trên format.

Ex:
scanf.c
 /* scanf example */  
#include <stdio.h>

int main ()
{
char str [80];
int i;

printf ("Enter your family name: ");
scanf ("%79s",str);
printf ("Enter your age: ");
scanf ("%d",&i);
printf ("Mr. %s , %d years old.\n",str,i);
printf ("Enter a hexadecimal number: ");
scanf ("%x",&i);
printf ("You have entered %#x (%d).\n",i,i);

return 0;
}

sscanf.c
 /* sscanf example */  
#include <stdio.h>

int main ()
{
char sentence []="Rudolph is 12 years old";
char str [20];
int i;

sscanf (sentence,"%s %*s %d",str,&i);
printf ("%s -> %d\n",str,i);

return 0;
}

fscanf.c
 /* fscanf example */  
#include <stdio.h>

int main ()
{
char str [80];
float f;
FILE * pFile;

pFile = fopen ("myfile.txt","w+");
fprintf (pFile, "%f %s", 3.1416, "PI");
rewind (pFile);
fscanf (pFile, "%f", &f);
fscanf (pFile, "%s", str);
fclose (pFile);
printf ("I have read: %f and %s \n",f,str);
return 0;
}


Đăng nhận xét