Completed and improved ex1_10 using a switch function.
This commit is contained in:
parent
d3262419a8
commit
d6f81778ef
1 changed files with 30 additions and 0 deletions
30
KNR C/ex1_10_improved.c
Normal file
30
KNR C/ex1_10_improved.c
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
#include <stdio.h>
|
||||
|
||||
/*Alternative (challenge) implementation of exercise 1-10 using a switch statement
|
||||
* as opposed to a series of if statements*/
|
||||
|
||||
int main(){
|
||||
int a = 0; /*Initializing a as zero; this doesn't matter because getchar is called at the top of the loop */
|
||||
|
||||
while (a != EOF){
|
||||
|
||||
a = getchar();
|
||||
|
||||
switch (a){
|
||||
case '\t':
|
||||
printf ("\\t");
|
||||
break;
|
||||
case '\\':
|
||||
printf ("\\\\");
|
||||
break;
|
||||
case '\b':
|
||||
printf ("\\b");
|
||||
break;
|
||||
case EOF: /*Required case for checking if a is EOF, since the loop actually tests whether a = EOF before refreshing a, thus allowing us to enter the loop with the value of a set to EOF */
|
||||
break;
|
||||
default:
|
||||
putchar (a);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue