编写程序输入一行元素统计有多少个单词,单词之间用空格隔开
时间: 2023-12-26 22:24:52 浏览: 72
可以使用字符串流(stringstream)来实现这个功能。具体步骤如下:
1. 读入一行字符串。
2. 创建一个字符串流对象,将读入的字符串传入。
3. 使用一个计数器变量,初始化为0。
4. 循环从字符串流中读取单词,每读取一个单词计数器加1。
5. 输出计数器的值。
以下是示例代码:
```c++
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string line;
getline(cin, line); // 读入一行字符串
stringstream ss(line); // 创建字符串流对象
int count = 0;
string word;
while (ss >> word) { // 循环从字符串流中读取单词
count++;
}
cout << "There are " << count << " words in the input." << endl; // 输出计数器的值
return 0;
}
```
相关问题
用 Dev-c++编写一个程序输入一行字符,统计其中有多少个单词。单词之间用一个或多个空格 分隔开。
以下是一个使用Dev-C++编写的程序,可以输入一行字符并统计其中的单词数目:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
int count = 0;
bool flag = true; // 标志位,表示是否在单词中
cout << "请输入一行字符:" << endl;
getline(cin, str);
for (int i = 0; i < str.length(); i++) {
if (str[i] == ' ') { // 遇到空格
flag = true;
} else if (flag) { // 进入新单词
count++;
flag = false;
}
}
cout << "该行字符中有 " << count << " 个单词。" << endl;
return 0;
}
```
该程序使用字符串类型存储输入的一行字符,使用计数器统计单词数目,使用标志位判断是否进入新的单词。在循环中遍历每个字符,遇到空格时将标志位设为 `true`,表示当前不在单词中,遇到非空格字符时检查标志位,如果为 `true`,则进入新的单词,同时将计数器加一,将标志位设为 `false`,表示当前在单词中。
注意:该程序只适用于单词之间用空格分隔的情况,对于其他分隔符可能需要进行修改。
编写fun函数,用来统计一行字符串单词个数.作为函数值放回。字符串用主函数输入,单词之间有空格隔开。用c++写
下面是实现该函数的 C++ 代码:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int fun(char *str) {
int cnt = 0;
int len = strlen(str);
bool in_word = false; // 标记是否在单词中
for (int i = 0; i < len; i++) {
if (str[i] == ' ') {
in_word = false;
} else if (!in_word) {
cnt++;
in_word = true;
}
}
return cnt;
}
int main() {
char str[] = "hello world! how are you?";
int word_cnt = fun(str);
cout << "Word count: " << word_cnt << endl; // 输出: Word count: 5
return 0;
}
```
该函数接收一个字符串指针作为参数,对该字符串进行处理,统计其中的单词个数。具体实现方法是遍历字符串中的每个字符,如果遇到空格则标记不在单词中,否则如果当前不在单词中则计数器加一,并标记在单词中。最后返回计数器的值。