fig08_14_mod.c (1341B)
1 /* Exercise 11.15 */ 2 3 /* Fig. 8.14: fig08_14.c 4 Using getchar and puts */ 5 #include <stdio.h> 6 #include <stdlib.h> 7 8 int main(void) 9 { 10 char c; /* variable to hold character input by user */ 11 char sentence[ 80 ]; /* create char array */ 12 int i = 0; /* initialize counter i */ 13 FILE *in = stdin, *out = stdout; 14 char input[15], output[15]; 15 16 fputs( "enter your choice: ", out ); 17 scanf("%d%*c", &i); 18 19 if(i == 1) { 20 fputs( "Input file: ", out ); 21 scanf("%s", input); 22 23 if( (in = fopen(input, "r")) == NULL) { 24 printf("%s: cannot open the file\n", input); 25 exit(-1); 26 } 27 28 fputs( "Output file: ", out ); 29 scanf("%s", output); 30 31 if( (out = fopen(output, "w")) == NULL) { 32 printf("%s: cannot open the file\n", output); 33 exit(-1); 34 } 35 } 36 else 37 /* prompt user to enter line of text */ 38 puts( "Enter a line of text:" ); 39 40 i = 0; 41 42 /* use getchar to read each character */ 43 while( ( c = fgetc(in) ) != '\n') { 44 sentence[ i++ ] = c; 45 } /* end while */ 46 47 sentence[ i++ ] = '\n'; /* insert a newline */ 48 sentence[ i ] = '\0'; /* terminate string */ 49 50 /* use puts to display sentence */ 51 fputs( "\nThe line entered was:\n", out ); 52 fputs( sentence, out ); 53 54 return 0; /* indicates successful termination */ 55 56 } /* end main */ 57