User:Fabien Labeyrie/C loops: Difference between revisions
No edit summary |
No edit summary |
||
Line 45: | Line 45: | ||
i++; | i++; | ||
} | } | ||
return 0; | |||
} | |||
</source> | |||
<br /> | |||
====Punctuation only filter==== | |||
The following code will replace any non-punctuation character by a space, using the ''ispunct'' function that tells if a character is a punctuation mark or not. | |||
<source> | |||
#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; | return 0; | ||
} | } | ||
</source> | </source> |
Revision as of 23:07, 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;
}
Punctuation only filter
The following code will replace any non-punctuation character by a space, using the ispunct function that tells if a character is a punctuation mark or not.
#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;
}