法一:用gets读入,因为gets可以读入任何字符且包括空格,直到 ‘\n’ 换行停止。注意:判断空格时用 ‘ ’, 注 : gets读入的必须是char数组 code: #include<bits/stdc++.h> using namespace std; int p,len=0,i,ans; char a[1212]; int main() { gets(a); len=strlen(a); for(int i=0;i<len;i++) if(a[i]==' ') ans++; //cout<<ans<<endl; cout<<len-ans<<endl; } 法二:用getchar读入,getchar也可以读入任何字符且包括空格,其余同上,但是getchar为字符中最高效的,gets易导致堆栈溢出 , getchar读入时要手动在末尾加入 空格 ‘\0’ ,其余读入法均自带。 gerchar读入时若不开char数组,则只读入第一位 code: #include<bits/stdc++.h> using namespace std; int p,len=0,i; char a[1212]; int main() { i=0; while((a[i]=getchar())!='\n') { i++; } a[i]='\0'; i=0; while(a[i]!='\0') { // putchar(a[i]); i++; if(a[i]==' ') len++; } if(a[0]==' ') 必须要特判第一位的空格,因为我在while中 i++ 在 if(a[i]==' ') 前面 len++; //putchar('\n'); cout<<i-len<<endl; //cout<<len<<endl; }