• Welcome to Jose's Read Only Forum 2023.
 

ProgEx22 - Use Of scanf and fscanf For Keyboard and File Input

Started by Frederick J. Harris, November 09, 2009, 01:14:33 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Frederick J. Harris


/*
  ProgEx22   --    (program should run as C or C++)
 
  Program shows console input with scanf of three signed decimal integers,
  followed by file output of the three input numbers with fprintf.  Then the
  file "Numbers.dat" is reopened in input mode "r' and the three integers are
  read in and displayed on screen.  The extra getchar() call at bottom will read
  the newline in that was left over in the keyboard buffer when you pressed
  [ENTER].  The original scanf call right after "Numbers.dat" was opened for
  writing would have left the newline character in the keyboard buffer after it
  was satisfied with getting the three integers.
 
  scanf is a very error prone input function to use, but is nonetheless somewhat
  useful.
 
  When you run this program type in three numbers separated with any kind of
  white space and press [ENTER].  For example,
 
  2 4 6 [ENTER]
 
  or
 
  2     4      6 [ENTER]   
 
  Note the '&' symbol in front of iNum1, iNum2 and iNum3.  scanf wants the
  address of these variables because they are 'output' parameters.  In other
  words, the function wants a pointer to the variables.
*/

#include <stdio.h>

int main(void)
{
int iNum1=0, iNum2=0, iNum3=0, iNum4=0, iNum5=0, iNum6=0;
FILE* fp;

fp=fopen("Numbers.dat","w");             
scanf("%d%d%d",&iNum1,&iNum2,&iNum3);
fprintf(fp,"%d\t%d\t%d\n",iNum1,iNum2,iNum3); 
fclose(fp);                   
fp=fopen("Numbers.dat","r"); 
fscanf(fp,"%d %d %d",&iNum4,&iNum5,&iNum6);     
printf("iNum4=%d\n",iNum4);
printf("iNum5=%d\n",iNum5);
printf("iNum6=%d\n",iNum6);             
fclose(fp);
getchar(); 
getchar();

return 0;                     
}

/*  --Output--
==============
2       4       6
iNum4=2
iNum5=4
iNum6=6
*/