如果问题实际上是愚蠢的,我很抱歉,但我刚开始学习C,并且没有人知道我能够提供帮助。 我应该统计stdin中的字母数,并说明每个字母被使用了多少次。 我们也期望使用计数器和fread方法。C程序返回意外的数字
编辑:伊戈尔帮助我与他的答案和程序现在几乎一切正确。小错误仍然存在:只有前10个字符被识别并计数,其他字符被忽略。输入必须大于10,否则不起作用。
我评论了我在代码中所做的更改,以便其他人可以跟踪我的错误。
我的代码是:
#include <stdio.h>
#include <ctype.h>
int main(){
char text[10];
int timesUsed[26]; // I initialized the array but didn't set the values to 0.
int timesUsed[26] = {0}; //this line corrected the issue with getting random numbers
int textLength = 0;
char *ptr;
while(fread(&text,sizeof(char),10,stdin)){
ptr = &text[0];
while(1){
if(isalpha(*ptr)){
textLength++;
*ptr = tolower(*ptr); //the original was only tolower(*ptr); which is useless
timesUsed[((char) *ptr) - 'a']++;
}
if(*ptr == '\n') goto end; //the original had here only one '='
/**ptr = '\0';*/
if(ptr == &text[10]) goto end; // on both
ptr ++;
}
}
end:
printf("Number of letters:%20d\n",textLength);
int i;
for(i=0;i<26;i++){
if(timesUsed[i]>0){
char thechar = (char) 'a' + i;
printf("The letter %c was used %5d time(s).\n",thechar,timesUsed[i]);
}
}
return 0;
}
哪个不打印预期的结果,它究竟是打印:
Testing testing testing testing testing testing M
Number of letters: 9
The letter e was used 2 time(s).
The letter g was used 1 time(s).
The letter i was used 1 time(s).
The letter n was used 1 time(s).
The letter s was used 1 time(s).
The letter t was used 3 time(s).
的变化进行的输出显得更有意义。尽管如此,还是有些失误
从未使用goto语句,除非直到您希望C社区中的每个人都可以降低您的... – Haris 2014-10-08 17:48:34
正确地格式化您的代码将有助于获得答案。我会帮忙,但我不想清理你的帖子。 – 2014-10-08 17:49:49
你也期望'if(ptr =&text [10])''? – P0W 2014-10-08 17:49:56