Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<string.h>
- #include<ctype.h>
- struct key {
- char *word;
- int count;
- };
- struct key keytab[] = {
- "auto",0,
- "break",0,
- "case",0,
- "char",0,
- "const",0,
- "continue",0,
- "default",0,
- "do",0,
- "double",0,
- "else",0,
- "enum",0,
- "extern",0,
- "float",0,
- "for",0,
- "goto",0,
- "if",0,
- "int",0,
- "long",0,
- "register",0,
- "return",0,
- "short",0,
- "signed",0,
- "sizeof",0,
- "static",0,
- "struct",0,
- "switch",0,
- "typedef",0,
- "union",0,
- "unsigned",0,
- "void",0,
- "volatile",0,
- "while",0
- };
- #define NKEYS (sizeof keytab / sizeof(struct key))
- /*binary search*/
- int binsearch (char * word, struct key tab[], int n) {
- int cond;
- int low, high, mid;
- low = 0;
- high = n -1;
- while (low <= high) {
- if ((cond = strcmp(word,tab[mid].word)) < 0)
- high = mid - 1;
- else if (cond > 0)
- low = mid + 1;
- else /*found it*/
- return mid;
- }
- return -1;
- }
- /*linear search*/
- int search (char* word, struct key tab[], int n) {
- int i;
- for (i = 0; i < n; ++i) {
- if (strcmp(word,tab[i].word) == 0) {
- return i;
- }
- }
- return -1;
- }
- #define BUFFSIZE 100
- char BUFF[BUFFSIZE]; /*array for ungetch*/
- int bufp = 0; /*buffer position, initialized to zero*/
- int getch (void) { /*get a (possibly pushed-back) character*/
- return (bufp > 0) ? BUFF[bufp--] : getchar();
- }
- void ungetch (int c) { /* push character back on input */
- if (bufp > BUFFSIZE) {
- printf("ungetch: too many characters\n"); /*if this is filled up*/
- }
- else {
- BUFF[bufp++] = c; /*if there's still room*/
- }
- }
- /*getword: get next word or character from input and read it into word*/
- int getword (char * word, int lim) {
- int c,getch(void);
- void ungetch(int);
- char * w = word;
- while (isspace(c = getch())) {
- ;
- }
- if (!isalpha(c)) {
- *w = '\0';
- return c;
- }
- for ( ; --lim > 0; w++) {
- if (!isalnum(*w = getch())) {
- ungetch(*w);
- break;
- }
- }
- *w = '\0';
- return w[0];
- }
- #define MAXWORD 100
- /*count C keywords*/
- int main (int argc, char * argv[]) {
- int n;
- char word[MAXWORD];
- while (getword(word,MAXWORD) != EOF) {
- printf("I've got past the beginning of the getword loop.\n");
- if(isalpha(word[0])) {
- printf("I'm past the word[0] condition.\n");
- if ((n = binsearch(word,keytab,NKEYS)) >= 0) { //the problem starts here
- printf("past the search condition.\n");
- keytab[n].count++;
- }
- }
- }
- for (n = 0; n < NKEYS; n++) {
- if (keytab[n].count > 0) {
- printf("%4d %s\n", keytab[n].count,keytab[n].word);
- }
- }
- return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement