【发布时间】:2014-01-21 21:07:16
【问题描述】:
#include <stdio.h>
int main (void)
{
int n;
printf("Give the number of words you want to input.");
scanf("%d",&n);
int letters[n],i,j,count,key,k;
char str[100];
//Scans each word, counts it's letters and stores it in the next available
//position in "letters" array.
for (i=0;i<n;i++)
{
j=0;
printf("Give the next word.");
do{
str[j] = getchar();
j++;
}while (str[j-1]!='\n');
str[j-1] = '\0';
letters[i] = j;
}
//Compacts the data by figuring out which cells have the same number of letters
for (i=0;i<n;i++)
{
key = letters[i];
count = 0;
for (j=i+1;j<=n;j++)
{
if (key==letters[j])
{
count += 1;
letters[j] = 0;
}
}
letters[i] = count;
}
//creates a histogram
i=0;
do{
printf("%d|",i);
for (j=1;j<=letters[i];j++)
{
printf("*");
}
printf("\n");
i++;
}while ((i<=n));
return 0;
}
我明白 getchar();读取,第一次输入 (\n) ,用户点击,给出他想要输入的单词数量,因此期望少一个单词。
另外,由于某种原因,最后我得到了一个无限循环。任何帮助和想法将不胜感激。提前致谢。
【问题讨论】:
-
您的代码直接保存到字符中,这会丢失有关 EOF 的信息,无论如何您都不会对其进行测试。这就是导致麻烦的事情。请记住:
getchar()返回一个int,它是char的值(被视为无符号)或表示 EOF 的负值(通常为 -1)。这是一个超出char的值,因此返回类型为int。我还没看还有什么问题。