/****************************************
输入一句话,统计输入的单词个数,例如
I love you!
有3个单词
***************************************/
#include <Windows.h>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main() {
int iCout = 0;
bool flag = TRUE;
char str[1024] = {'\0'};
char strTmp;
cout << "请输入一句话:";
//cin >> str; I LOVE YOU
//scanf_s("%s",str,1024);//scanf_s读入的字符串当遇到空格时就截止了,故只能用gets
gets_s(str, sizeof(str));//读入一行的字符串,直到遇到回车换行符
for (int i = 0; i < strlen(str); i++) {
strTmp =str[i];
if (strTmp ==' ' && flag==FALSE) {
flag = TRUE;
}
else if (strTmp != ' ' && flag == TRUE) {
iCout++;
flag = FALSE;
}
}
cout << "输入的语句有" << iCout << "单词"<<endl;
system("pause");
return 0;
}
运行结果截图如下