User:Lieven Van Speybroeck/Prototyping/4-C-Loops

From XPUB & Lens-Based wiki

Exercises on C_Loops:


Exercise 1: Write a program that adds line numbers to each line given to it via stdin.

this is pretty straightforward. While fgets goes through the whole file, use a loop to keep track of the amount of lines it's gone through and at which line it is. Then print this line number first before printing the string fgets finds...

#include "stdio.h"
#include "string.h"
#define MAXLINE 1000
 
int main() {
	int i=0;
	char line[MAXLINE];
	while (fgets(line, MAXLINE, stdin)) {
		i++;
		printf("% 4d\t%s", i, line);
	}
}

This would output the following when executed in the terminal (using the file itself as input):

   1	#include "stdio.h"
   2	#include "string.h"
   3	#define MAXLINE 1000
   4	 
   5	int main() {
   6		int i=0;
   7		char line[MAXLINE];
   8		while (fgets(line, MAXLINE, stdin)) {
   9			i++;
  10			printf("% 4d\t%s", i, line);
  11		}
  12	}

One thing i'd like to do to improve this script, is make the padding value of the line numbers dependent on the amount of lines in the input file. So a file with 1200 lines would have a padding of 4, while a file of 20 lines would have a padding of 2. To do this, you'd first have to go through the whole file, count the lines and put them in a variable. Then read the amount of (array) characters of this variable, store this number (1023 would be "4"), and then go through the file again to print it with the line numbers and use the stored value as the padding value. But there's 2 major things that i can't figure out:

  • how to convert an integer into a string (to be able to get the strlen of the number of lines that were counted)
  • how to make fgets go through the same input file twice (it seems to be able to go through stdin only once)


Exercise 2: Create a program that prints only the punctuation of a file (it a character is not punctuation, print a space.

This can be done easily with an "if else" nested within the loop that goes through all the characters of a file:

#include "stdio.h"
#include "string.h"
#define MAXLINE 1000
 
int main () {
    char line[MAXLINE];
    int linelen;
    int i;
    while (fgets(line, MAXLINE, stdin)) {
        linelen = strlen(line);
        for (i=0; i<linelen; i++) {
		if (ispunct(line[i])) {
			printf("%c ", line[i]);
		}
		else printf(" ");
        }
        printf("\n");
    }
     return 0;
}

This would give an output like this in terminal (using the file itself as input):

#         "      .  "  
#         "       .  "  
#                     
  
         ( )  {  
             [        ] ;  
               ;  
         ;  
          (      (     ,         ,       ) )  {  
                =        (     ) ;  
            (  =  ;   <        ;   + + )  {  
         (        (     [  ] ) )  {  
             ( " %   " ,      [  ] ) ;  
      }  
                 ( "  " ) ;  
        }  
              ( " \  " ) ;  
    }  
             ;  
}