User:Fabien Labeyrie/C loops: Difference between revisions

From XPUB & Lens-Based wiki
(Created page with "Category:prototyping Category:2011_P1.01 __NOTOC__ ==C loops== ====fgets function==== The following code output the length of each line, but it actually outputs lines t...")
 
No edit summary
Line 20: Line 20:
         linelen = strlen(line);
         linelen = strlen(line);
         printf("line is %d characters long\n", linelen);
         printf("line is %d characters long\n", linelen);
    }
    return 0;
}
</source>
<br />
====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.
<source lang="C">
#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;
     return 0;
}
}
</source>
</source>

Revision as of 23:00, 8 November 2010


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;
}