so i'm reading an exercise on structures in the C k&R book.
it says to modify getword routine in order to take in to consideration
underscores, comments etc.
i'm trying to start small (i.e check for begining of comment and set X to 5 if found) before writing the actual code but it seems hard apparently. heres the code:
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXWORD 100
#define NKEYS (sizeof keytab/sizeof(keytab[0]))
#define CINDEX 12
#define BUFSIZE 100
char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */
int getch(void) /* get a (possibly pushed-back) character */
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) /* push character back on input */
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
struct key{
char *word;
int count;
} keytab[] = {
{"auto", 0},
{"break", 0},
{"case", 0},
{"char", 0},
{"const", 0},
{"continue", 0},
{"default", 0},
{"for", 0},
{"unsigned", 0},
{"signed", 0},
{"volatile", 0},
{"void", 0},
{"comments", 0},
{"while", 0}
};
int getword(char *, int);
int binsearch(char *, struct key *, int);
int main(){
int n;
char word[MAXWORD];
while(getword(word, MAXWORD) != EOF)
if( isalpha(word[0]))
if ( (n = binsearch(word, keytab, NKEYS)) >= 0)
keytab[n].count++;
for( n = 0; n < NKEYS; n++ )
printf("%4d %s\n", keytab[n].count, keytab[n].word);
return 0;
}
int getword(char *word, int lim){
int c, getch(void);
void ungetch(int c);
char *w = word;
while(isspace(c = getch()))
;
if(c != EOF || c == '/'){
if(c == '/'){
c = getch();
if( c == '*'){
int x = 5;
}
}
*w++ = c;
}
if (!isalpha(c)){
*w = c;
return c;
}
for(; --lim > 0; w++)
if(!isalnum(*w = getch())){
ungetch(*w);
break;
}
*w = '\0';
return w[0];
}
int binsearch(char *word, struct key keytab[], int n){
int cond;
int low, mid, high;
low = 0;
high = n - 1;
while(low <= high){
mid = (low+high)/2;
if( (cond = strcmp(word, keytab[mid].word)) < 0)
high = mid - 1;
else if ( cond > 0)
low = mid + 1;
else
return mid;
}
return -1;
}
when i step through the code in a debugger, i first input '/' then '*' without quotes and i assume this code
Code:
if(c == '/'){
c = getch();
if( c == '*'){
int x = 5;
}
}
should handle it, how ever, execution goes thus;
Code:
]if(c == '/'){ // evaluates as TRUE so rest code executes
c = getch(); // debugger just skips this, i don't get to input '*'
if( c == '*'){ // thus, this is is skipped
int x = 5;
}
}
what i'm i doing wrong please?