代码实现:
#include<iostream>
#include<Windows.h>
#include<string>
using namespace std;
int main(void) {
char str[100];
cout << "输入有个字符串:";
gets_s(str,sizeof(str));
int i = 0;
int sum = 0; //记录单词个数
//先读取连续的空格
while (str[i] == ' ') i++;
while (str[i] != '\0') {
//连续的非空格是单词
while (str[i] != ' ') i++;
while (str[i] == ' ') i++;
sum++; //单词个数加 1
}
cout << sum << endl;
system("pause");
return 0;
}