c++编写一个单词统计程序
时间: 2024-03-14 12:43:12 浏览: 22
好的,下面是一个简单的 C++ 单词统计程序:
```c++
#include <iostream>
#include <string>
#include <map>
#include <sstream>
using namespace std;
int main() {
// 初始化计数器
map<string, int> wordCount;
// 读入输入文本
stringstream ss;
string line;
while (getline(cin, line)) {
ss << line << " ";
}
// 分割单词并统计
string word;
while (ss >> word) {
++wordCount[word];
}
// 输出结果
for (const auto& pair : wordCount) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
```
该程序首先读入一段文本,然后将其分割成单词,并统计每个单词出现的次数,最后输出结果。其中使用了 `map` 来记录每个单词的计数器。
相关问题
c++编写一个单词统计程序: 1)打开四个文本文档,读取数据; 2)统计英文单词的数量。
好的,下面是一个 C++ 单词统计程序,可以打开四个文本文档,读取数据,统计英文单词的数量:
```c++
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <map>
using namespace std;
// 统计单词数量的函数
void countWords(map<string, int>& wordCount, string& line) {
string word;
stringstream ss(line);
while (ss >> word) {
// 剔除单词中的标点符号
while (!isalpha(word.back())) {
word.pop_back();
}
// 统计单词
++wordCount[word];
}
}
int main() {
// 打开四个文本文档
ifstream file1("text1.txt");
ifstream file2("text2.txt");
ifstream file3("text3.txt");
ifstream file4("text4.txt");
// 初始化计数器
map<string, int> wordCount;
// 读取文本并统计单词
string line;
while (getline(file1, line)) {
countWords(wordCount, line);
}
while (getline(file2, line)) {
countWords(wordCount, line);
}
while (getline(file3, line)) {
countWords(wordCount, line);
}
while (getline(file4, line)) {
countWords(wordCount, line);
}
// 输出结果
cout << "英文单词数量:" << wordCount.size() << endl;
return 0;
}
```
该程序通过 `ifstream` 打开四个文本文档,然后逐行读取文本并统计单词数量。其中 `countWords` 函数用于分割单词,并统计每个单词出现的次数。最后,程序输出统计结果,即英文单词的数量。注意,为了准确地统计单词数量,程序在分割单词时剔除了单词中的标点符号。
请使用C++编写一个程序,输入一个字符串,统计其单词个数及字母个数
以下是使用C++编写的程序,可以输入一个字符串,统计其单词个数及字母个数:
```c++
#include <iostream>
using namespace std;
int main() {
string str;
getline(cin, str); // 读入一行字符串
int wordCount = 0; // 单词个数
int letterCount = 0; // 字母个数
bool inWord = false; // 是否在单词中
for (int i = 0; i < str.length(); i++) {
char c = str[i];
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') { // 如果是字母
letterCount++;
if (!inWord) { // 如果不在单词中,说明进入了新单词
wordCount++;
inWord = true;
}
} else { // 如果不是字母
inWord = false; // 不在单词中
}
}
cout << "单词个数:" << wordCount << endl;
cout << "字母个数:" << letterCount << endl;
return 0;
}
```
程序先读入一行字符串,然后遍历字符串中的每个字符。如果当前字符是字母,则累加字母个数,并检查是否进入了新单词。如果当前字符不是字母,则不在单词中。最后输出单词个数和字母个数。