如果問題實際上是愚蠢的,我很抱歉,但我剛開始學習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