#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),用户点击,给出他想要输入的字数,因此期望少一个单词。
另外,由于某种原因,我在最后得到了一个信息循环。任何帮助和想法都将不胜感激。提前谢谢。
发布于 2014-01-21 21:31:16
将代码的第一个块更改如下:
(测试getchar的输出,只在没有EOF的情况下继续)
for (i=0;i<n;i++)
{
j=0;
printf("Give the next word.");
do{
a = getchar();
if(a >= 0)
{
str[j] = a;
j++;
}
else break;
}while (str[j-1]!='\n');
str[j-1] = '\0';
letters[i] = j;
}但是关于您的问题:如何替换getchar();?你考虑过使用scanf()吗?
编辑
下面是一个使用scanf()和printf()提示输入,然后显示输入的简单示例。它将允许用户输入整个单词或句子(最多80个字符),直到输入'q‘为止。不完全是你正在做的,但你应该能够使它适应你的代码.(运行这个)
int main(void)
{
char buf[80]={""};
while( strcmp(buf, "q") != 0) //enter a 'q' to quit
{
buf[0]=0;
printf("enter string:\n");
scanf("%s", buf);
printf("%s\n", buf);
}
}发布于 2014-01-21 21:16:24
在第一个循环中更新字母计数不是更容易吗?
memset(letters, 0, n);
for (i=0;i<n;i++)
{
char* s = str;
int j=0;
printf("Give the next word.");
do{
*s = getchar();
++j;
}while (*(s++)!='\n');
s[-1] = '\0';
letters[j-1]++;
}因此,第二个循环将是不必要的。
发布于 2014-01-21 21:43:30
以下两行有错误的结束条件;应该是<n,而不是<=n。当前,它们检索未初始化的数组元素。由于您将str声明为局部变量,该元素通常被垃圾填充,即一个非常大的随机数。这也许可以解释为什么最后一个循环要花很长时间(但可能不是永远)才能完成。
for (j=i+1;j<=n;j++)
}while ((i<=n));另外,我假设柱状图的第n行应该包含有n个字母的单词数?这不是你现在要做的。
letters[i] = count;这一行应该是:
letters[key] = count;但是,要使其工作,您应该而不是覆盖相同的数组letters;您必须为您的直方图声明一个新的数组,否则第二个循环将破坏它自己的输入。
顺便说一下,str看起来完全是多余的。它是否用于调试目的?
https://stackoverflow.com/questions/21269105
复制相似问题