在學校相當多的幾年後,我重新開始編碼,並且我試圖在C中編寫一個程序文本中有多少個n字母單詞,將它們存儲到一個長度爲n的數組中,然後將它們打印出來。爲了保持簡單,我假定n是b/w 1和10,每個單詞由一個空格分隔。C程序用於計算嵌套在while循環中的文本中的n個字母單詞的數量
下面是代碼,但是,似乎我的程序永遠不會從內部while循環中跳出,因此屏幕上不會顯示任何內容。我試圖在該循環的末尾打印一些東西來測試它,出於某種原因,程序打印的次數與有字符(包括空格,內部條件應該捕獲並退出)的次數相同。我在這裏忽略了什麼嗎?
main()
{
int c, i, j, counter;
counter = 0;
int wlength [10];
for (i=0; i<10; ++i) //initialize array
wlength[i]=0;
while((c=getchar())!=EOF){ // keep taking input until end of file
while (c!=' '){ //keep counting until you reach the end of the word
++counter;
c=getchar();
}
wlength [counter-1]++; //increment the counter for that word length
counter=0 ; //reset the counter for the next word
}
for (j=0;j<10;++j) //print the array
printf("%d ", wlength[j]);
您需要測試EOF。你只在外環測試。 – stark
是不是每行的最後一個字符是換行符(\ n還是\ r \ n)? – Roger
嘗試'while(c!=''&& c!='\ n'&& c!= EOF){'而不是'while while(c!=''){' – BLUEPIXY