User:Fabien Labeyrie/C loops: Difference between revisions

From XPUB & Lens-Based wiki
No edit summary
No edit summary
 
(One intermediate revision by the same user not shown)
Line 3: Line 3:
__NOTOC__
__NOTOC__
__NOEDITSECTION__
__NOEDITSECTION__
==<span style="color:#00FF00">C loops</span>==
<div style="width: 600px; font-family:Arial">
==<span style="color:#0B0080">C loops</span>==
<hr style="height:5px; margin-top:-15px; background-color:#FFF">
<br />


====fgets function====
====fgets function====
Line 81: Line 84:
</source>
</source>


<br />
====Results====
The output is masterpiece of [http://en.wikipedia.org/wiki/ASCII_art ASCII art] :
The output is masterpiece of [http://en.wikipedia.org/wiki/ASCII_art ASCII art] :


Line 91: Line 96:
           }            ( " \  " ) ;      }              ;  }
           }            ( " \  " ) ;      }              ;  }
</source>
</source>
</div>

Latest revision as of 22:05, 6 April 2011


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


Results

The output is masterpiece of ASCII art :

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