使用c++读入一个英文文本文件,英文中有字母、数字、其它字符,无汉字,文件有多行(程序要能处理至少4行文字,附件中有参考素材)。 2.编写函数实现:统计字母的出现频度,并显示结果。(大小写算同一字母) 3.编写函数实现:统计其中单词的个数,并显示结果。(单词个数以WORD统计作为参考,不一定100%相同。) 4.编写函数实现:找出最长的单词,并显示单词及其长度。 5.编写函数实现:统计出现的整数,存入一维数组,并显示结果。 (1) 比如文件中有两行: "abc 123 W 6 www 9." "teacher 10 student 7." (2) 分析得到5个数:123、6、9、10、7。 (3) 定义数组int a[1000] (4) a[0]=123,a[1]=6,a[2]=9,a[3]=10,a[4]=7。 注:可以利用下标或字符型指针处理字符串。
时间: 2024-01-26 13:03:11 浏览: 72
以下是一个基础版的实现,可以根据需求进行修改:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <sstream>
using namespace std;
// 统计字母的出现频度
void countLetters(const string& text, map<char, int>& freq) {
for (char c : text) {
if (isalpha(c)) { // 只统计字母
c = tolower(c); // 转换为小写字母
freq[c]++;
}
}
}
// 统计单词的个数
int countWords(const string& text) {
stringstream ss(text);
string word;
int count = 0;
while (ss >> word) {
count++;
}
return count;
}
// 找出最长的单词
string findLongestWord(const string& text) {
stringstream ss(text);
string word, longestWord;
int maxLength = 0;
while (ss >> word) {
int length = word.length();
if (length > maxLength) {
maxLength = length;
longestWord = word;
}
}
return longestWord;
}
// 统计出现的整数
void countIntegers(const string& text, vector<int>& integers) {
stringstream ss(text);
string word;
while (ss >> word) {
if (isdigit(word[0])) { // 判断是否为数字
int num = stoi(word);
integers.push_back(num);
}
}
}
int main() {
ifstream infile("input.txt");
string line;
map<char, int> freq;
int wordCount = 0;
string longestWord;
int maxLength = 0;
vector<int> integers;
while (getline(infile, line)) {
countLetters(line, freq);
wordCount += countWords(line);
string word = findLongestWord(line);
int length = word.length();
if (length > maxLength) {
maxLength = length;
longestWord = word;
}
countIntegers(line, integers);
}
// 输出字母频度
cout << "Letter Frequency:" << endl;
for (auto p : freq) {
cout << p.first << ": " << p.second << endl;
}
// 输出单词个数
cout << "Word Count: " << wordCount << endl;
// 输出最长的单词及其长度
cout << "Longest Word: " << longestWord << ", Length: " << maxLength << endl;
// 输出整数
cout << "Integers: ";
for (int i : integers) {
cout << i << " ";
}
cout << endl;
return 0;
}
```
其中,`countLetters`函数使用`map`来统计字母的出现频度,`countWords`函数使用`stringstream`来分离单词并统计个数,`findLongestWord`函数遍历单词并记录最长单词,`countIntegers`函数使用`stringstream`来判断数字并存入向量中。在`main`函数中遍历每一行文本,调用上述函数来实现各项功能。
阅读全文