【发布时间】: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];的用途是什么?