【问题标题】:Why the output of this C program sticks?为什么这个 C 程序的输出会卡住?
【发布时间】:2015-04-21 20:39:26
【问题描述】:

我正在尝试制作一个程序来计算输入中存在的关键字数量,类似于第 6.3 节结构数组中 Dennis Ritchie 的 C 编程语言示例中的示例。这是我的代码-

#include <stdio.h>
#include <ctype.h>
#include <string.h>
int binsearch(char *s, struct key mt[], int lim);
int getch(void);
void ungetch(int );
int getword(char *word, int lim);
struct key{
    int count;
    char *word;
}keys[] = { { 0, "break" }, { 0, "int" }, { 0, "return" } };

int main()
{
        int n;
    char word[20];
    while (getword(word, 20) != EOF)
        if (isalpha(word[0]))
        if ((n = binsearch(word, keys, 3)) >= 0)
            keys[n].count++;
        for (n = 0; n < 3; n++)
            if (keys[n].count>0)
            printf("%s count=%d", keys[n].word, keys[n].count);
    return 0;
}
int getword (char *word, int lim) 
{
    int c;
    char *w = word;
    while (isspace(c = getch()))
        ;
    if (c != EOF)
        *w++ = c;
    if (!isalpha(c)){
        *w = '\0';
        return c;
    }
    for (; --lim > 0;w++)
    if (!isalnum(*w = getch())){
        ungetch(*w);
        break;
    }
    *w = '\0';
    return word[0];
}
char buffer[400];
int t = 0;

int getch(void)
{
    return ((t == 0) ? getchar() : buffer[--t]);
}
void ungetch(int c)
{
    buffer[t++] = c;
}
int binsearch(char *s, struct key mt[], int lim)
{
    int cond;
    int min = 0;
    int max = lim - 1;
    int mid = (min + max) / 2;
    while (min <= max)
    {
        if ((cond = strcmp(s, mt[mid].word)) > 0)
            min = mid + 1;
        else if (cond < 0)
            max = mid - 1;
        else
            return mid;
    }
    return -1;
}

在 Visual Studio Express 2013 中编译此代码时,输​​出终端仅接受第一行,按 Enter 后没有任何反应。无法输入更多数据,也没有任何输出。请帮我找出问题所在。

【问题讨论】:

  • "%s count=%d" 更改为"%s count=%d\n"
  • 这段代码中char buffer[400]; 的用途是什么?

标签: c search binary


【解决方案1】:

谢谢大家。我发现了问题所在。实际上在 binsearch 函数中,我在 while 循环之外定义了 mid=(min+max)/2。

【讨论】:

    猜你喜欢
    • 2013-03-23
    • 2019-11-23
    • 2011-07-10
    • 2012-10-11
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 2017-01-19
    • 2013-03-10
    相关资源
    最近更新 更多