代码之家  ›  专栏  ›  技术社区  ›  Bar K

c程序的意外行为,试图从K&R解决E6-2

  •  1
  • Bar K  · 技术社区  · 9 年前

    练习6-2。 编写一个程序,读取C程序并按字母顺序打印每组 变量名在前6个字符中相同,但在后面的某个地方不同。不算数 字符串和注释中的单词。使6成为可以从命令行设置的参数。(来自K&R)

    我开始练习了,但我一开始就陷入了困境。我试图获取整个输入并将其逐行保存在数组中,然后将数组中的指针指向保存的行。后来我想到为每个单词分配空间,并将它们复制到一棵树上。然而,在以下代码中,当我输入时:

    abc定义;'Ctrl-Z'

    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    
    #define MAXLINE 100
    #define MAXWORDS 10
    
    int read_input(char *[]);
    
    int main(int argc, char *argv[])
    {
        char *variables[MAXWORDS] = {0};
        int i;
        int tmp;
    
    
        while((tmp = read_input(variables)) != EOF){
            for(i=0; i < tmp; i++){
                printf("%s ",*(variables+i));
            }
        }
    
    
        return 0;
    }
    
    
    /* read_input: mapping all the input words into *variables[], and returning the number of the words + 1 */
    int read_input(char *variables[]){
        static char s[MAXLINE];
        int tmp;
        int i, j;
    
        i = 0;
        if((tmp = getline(s, MAXLINE)) == EOF)
            return EOF;
    
        for(j = 0; j < MAXWORDS && s[i] != '\0'; j++){ /* it does'nt work when j = MAXWORDS because the rest of the line is not saved */
            while(!isalpha(s[i]))
                i++;
            *(variables+j) = &s[i];
            while(isalnum(s[i]) || s[i] == '_')
                i++;
            if(s[i] == '\0')
                continue;
            s[i++] = '\0';
        }
        return j;
    }
    
    /* getline: read a line into s, return length */
    int getline(char *s,int lim)
    {
        static char end; /* static typed char that saves if the last not saved 'c' was an EOF */
        char c;
        int i;
        if(end == EOF){ /* the last input character was an EOF */
            end = 0;
            return EOF;
        }
        for (i=0; i < lim-1 && (c=getchar())!=EOF && c!=';'; ++i)
            s[i] = c;
        s[i] = '\0';
        if(i > 0 && c == EOF)
            end = EOF;
        else if(i == 0 && c == EOF){
            printf("!");
            return EOF;
        }
        else
            return i;
    
    }
    

    程序不会立即停止,main的while循环会要求另一个输入……我做错了什么?

    1 回复  |  直到 9 年前
        1
  •  0
  •   Armali    8 年前

    你没有做错什么。由于C stdio库函数的通常设计,只有在前面没有未读输入的情况下才能识别EOF,因此必须键入 进来 Ctrl键 - Z Ctrl键 - Z Ctrl键 - Z .