Implemented a suggestion from Affine to replace the many if statements with a single switch and only ever call getchar at one point in the code.
This commit is contained in:
parent
43f172da21
commit
d3ce211f14
1 changed files with 18 additions and 21 deletions
|
|
@ -1,34 +1,31 @@
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
|
||||||
|
|
||||||
/*A really silly way to complete exercise 1-10 of KNR C*/
|
/*A really silly way to complete exercise 1-10 of KNR C*/
|
||||||
|
|
||||||
int main(){
|
int main(){
|
||||||
|
|
||||||
int a = getchar(); /*There is, unfortuately, no immediately obvious way to avoid repeating this since we need to initialize 'a' in order to have valid data for everything beyond this line*/
|
|
||||||
|
|
||||||
if (a == EOF){ /*Check whether first character is EOF*/
|
|
||||||
printf ("Error: No data to parse. \n Exiting.");
|
|
||||||
EXIT_FAILURE; /*Exit if there is no data to parse.*/
|
|
||||||
}
|
|
||||||
|
|
||||||
loop_start: /*Goto will circle back to the next line if a != EOF*/
|
loop_start: /*Goto will circle back to the next line if a != EOF*/
|
||||||
if (a == '\t' || a == '\b' || a == '\\'){
|
|
||||||
if (a == '\t')
|
|
||||||
printf("\\t");
|
|
||||||
if (a == '\b')
|
|
||||||
printf("\\b");
|
|
||||||
if (a == '\\')
|
|
||||||
printf ("\\\\");
|
|
||||||
} else {
|
|
||||||
putchar(a);
|
|
||||||
}
|
|
||||||
|
|
||||||
a = getchar();
|
int a = getchar();
|
||||||
|
|
||||||
|
switch (a){
|
||||||
|
case EOF:
|
||||||
|
break;
|
||||||
|
case '\t':
|
||||||
|
printf("\\t");
|
||||||
|
break;
|
||||||
|
case '\b':
|
||||||
|
printf("\\b");
|
||||||
|
break;
|
||||||
|
case '\\':
|
||||||
|
printf("\\\\");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
putchar (a);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
if (a != EOF) /*Only trigger next loop if 'a' contains valid data.*/
|
if (a != EOF) /*Only trigger next loop if 'a' contains valid data.*/
|
||||||
goto loop_start;
|
goto loop_start;
|
||||||
|
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue