User:Fabien Labeyrie/C loops

From XPUB & Lens-Based wiki


C loops

fgets function

The following code output the length of each line, but it actually outputs lines that are one character longer. It might be that the hard return character is taken into account.

#include "stdio.h"
#include "string.h"
#define MAXLINE 1000

int main () {
    int i=0;
    int linelen;
    char line[MAXLINE];
    while (fgets(line, MAXLINE, stdin)) {
        linelen = strlen(line);
        printf("line is %d characters long\n", linelen);
    }
    return 0;
}


Line numbering

Using the padding with %0?d (the ? stands for how many zeros you want to add in front of your numbering) will help us to number the lines in an output.

#include "stdio.h"
#include "string.h"
#define MAXCHAR 200
 
int main () {
    int i=0;
    int linelen;
    char line[MAXCHAR];

    while (fgets(line, MAXCHAR, stdin)) {
        linelen = strlen(line);
        printf("%02d %s", i, line);
	i++;
    }
    return 0;
}