c++输入一行字符,统计其中有多少个单词,每两个单词之间以空格隔开。
时间: 2023-12-26 13:22:51 浏览: 37
可以使用C++的string和stringstream库来实现输入一行字符并统计单词个数的功能。具体代码如下:
```cpp
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string line;
getline(cin, line); // 输入一行字符
stringstream ss(line); // 将字符串转换为stringstream对象
int wordCount = 0;
string word;
while (ss >> word) { // 每次读取一个单词
wordCount++;
}
cout << "单词个数为:" << wordCount << endl;
return 0;
}
```
以上代码中,我们首先使用getline函数读取一行字符,然后使用stringstream库将字符串转换为stringstream对象,方便我们按照空格分割字符串并统计单词个数。最后输出单词个数即可。
相关问题
c++输入一行字符,统计其中有多少个单词,单词之间用空格分隔开
以下是两种C++统计单词个数的例子:
1. 使用while循环和getchar()函数
```cpp
#include <stdio.h>
int main() {
char ch;
int num = 0;
printf("请输入一行字符,单词之间用一个空格分隔开\n");
while ((ch = getchar()) != '\n') {
if (ch == ' ') {
num++;
}
}
printf("该行字符有%d个单词", ++num);
return 0;
}
```
2. 使用for循环和gets()函数
```cpp
#include <stdio.h>
void main() {
char a[80];
int i, num = 0, word = 0;
printf("input:");
gets(a);
for (i = 0; a[i] != '\0'; i++) {
if (a[i] == ' ') {
word = 0;
} else if (word == 0) {
num++;
word = 1;
}
}
printf("num=%d\n", num);
}
```
输入一行字符,统计其中有多少个单词,单词之间用空格隔开,c++
可以使用 C++ 的字符串流 stringstream 来实现单词的统计,具体代码如下:
```c++
#include <iostream>
#include <sstream>
using namespace std;
int countWords(string line) {
stringstream ss(line);
string word;
int count = 0;
while (ss >> word) {
count++;
}
return count;
}
int main() {
string line = "This is a test sentence.";
int wordCount = countWords(line);
cout << "There are " << wordCount << " words in the input line." << endl;
return 0;
}
```
该程序中的 countWords 函数接受一个字符串作为参数,返回该字符串中单词的个数。该函数首先使用 stringstream 对象 ss 来将输入字符串 line 进行分词,然后使用 while 循环遍历所有的单词,累计单词的数量并返回。在 main 函数中,我们传入一个测试用例字符串,并输出该字符串中单词的数量。