10. 统计单词 输入一行字符,以回车结束,统计其中单词的个数。各单词之间用空格分隔,空格数可以是多个。 用C++实现
时间: 2023-12-21 11:34:29 浏览: 57
以下是使用 C++ 实现统计单词个数的代码示例:
```cpp
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int countWords(string input) {
int count = 0;
stringstream ss(input);
string word;
while (ss >> word) {
count++;
}
return count;
}
int main() {
string input;
cout << "请输入一行字符:";
getline(cin, input);
int wordCount = countWords(input);
cout << "单词个数为:" << wordCount << endl;
return 0;
}
```
以上代码会提示用户输入一行字符,然后通过调用 `countWords()` 函数统计其中的单词个数。该函数使用 `std::stringstream` 来分割输入的字符串,并通过循环逐个读取单词,最后返回单词个数。注意,该代码假设单词之间用空格分隔。
相关问题
用c++输入一行字符 分别统计出其中的英文字母,空格,数字和其他字符的个数
```c++
#include<iostream>
using namespace std;
int main(){
char ch;//定义字符变量
int letter = 0, space = 0, digit = 0, other = 0;//分别统计英文字母、空格、数字和其他字符的个数
cout<<"请输入一行字符:";
while(cin.get(ch)){//不断循环输入字符,直到输入结束
if(ch>='a' && ch<='z' || ch>='A' && ch<='Z'){//判断是否为英文字母
letter++;
}
else if(ch==' '){//判断是否为空格
space++;
}
else if(ch>='0' && ch<='9'){//判断是否为数字
digit++;
}
else{//其他字符
other++;
}
if(ch=='\n'){//遇到换行符结束循环
break;
}
}
cout<<"英文字母个数:"<<letter<<endl;
cout<<"空格个数:"<<space<<endl;
cout<<"数字个数:"<<digit<<endl;
cout<<"其他字符个数:"<<other<<endl;
return 0;
}
```
输入一行字符,分别统计出其中英文字母、空格、数字何其他字符的个数
以下是Python代码,可以实现输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数:
```python
s = input("请输入一行字符:")
letters = 0
space = 0
digit = 0
others = 0
for c in s:
if c.isalpha():
letters += 1
elif c.isspace():
space += 1
elif c.isdigit():
digit += 1
else:
others += 1
print("英文字母个数:", letters)
print("空格个数:", space)
print("数字个数:", digit)
print("其他字符个数:", others)
```