2 回答

TA貢獻1829條經驗 獲得超9個贊
線路if(str[i]==" "){錯了。
" "是一個字符串,它由兩個字節組成:空格字符和終止 NUL 字符。
你應該if(str[i]==' '){改用。
' '是一個字符,你應該將它與str[i], 這也是一個字符進行比較。
此外,您似乎忘記在數字后打印空格字符。
還有一點是,即使最后一個單詞后面沒有空格字符,您也應該打印最后一個單詞的長度。
順便說一句,您不應該使用gets(),它具有不可避免的緩沖區溢出風險,在 C99 中已棄用并從 C11 中刪除。您應該使用fgets(), 取而代之的是緩沖區大小。 fgets()將讀取的換行符保存到緩沖區,gets()而不保存,因此如果您不想要換行符,則應刪除它們。
更正代碼的示例:
#include <stdio.h>
#include<string.h>
int main()
{
int i,n,count=0;
char str[20 + 1]; // allocate one more character for a newline character
char* lf; // for searching for a newline character
fgets(str, sizeof(str), stdin); // use fgets() instead if gets()
if ((lf = strchr(str, '\n')) != NULL) *lf = '\0'; // remove a newline character if one exists
n=strlen(str);
for(i=0;i<=n;i++){ // change < to <= for processing the terminating NUL character
if(str[i]==' ' || str[i]=='\0'){ // compare with a character, not a string
if (count>0) printf("%d",count); // avoid duplicate printing for duplicate space characters
if(i+1<n) printf(" "); // print a space if the string continues
count=0;
}else{
printf("%c",str[i]);
count++;
}
}
return 0;
}
添加回答
舉報