User:Lieven Van Speybroeck/Prototyping/4-C-Loops
An attempt to solving the 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 this when executed in the terminal:
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 line 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 and 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 a few things that i can't figure out:
- how to convert an integer into a character variable (to be able to get the strlen of the amount of lines that were counted)
- how to make fgets go through the same input file twice (it seems to be able to go through the input only once)