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

标签 c kernighan-and-ritchie

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

我开始做这个练习,但我卡在了开头。我试图获取整个输入并将其逐行保存在数组中,然后将数组中的指针指向保存的行。后来想到给每个词分配空间,copy到一棵树上。但是,在我作为输入输入时的以下代码中:

abc def;'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 循环会要求另一个输入...我做错了什么?

最佳答案

你没有做错任何事。由于 C stdio 库函数的通常设计,EOF 只有在前面没有未读输入时才会被识别,因此您必须键入 Enter Ctrl-Z Ctrl-ZCtrl-Z

关于c - c 程序的意外行为,试图从 K&R 解决 E6-2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34641404/

相关文章:

c - 如何确保 strtol() 已成功返回?

c - K&R C 练习 1-18 无输出/调试问题

c - strcmp : fields within lines

c - 最长的字符串

c - 取消引用双指针并使用索引运算符

c - 在 C 中,检查是否存在名称与模式匹配的文件

c - 在 C 中的用户定义函数中将文本文件中的数字读取到数组

c - 关于 struct 数组作为 gcc 和 vc 编译的参数

C-K&R 表达式 : evaluate a reverse Polish expression from the command line

c - 程序可以编译,但在提供输入时不执行任何操作