文章中字符出现概率统计c++fstream 库
时间: 2024-02-23 08:59:11 浏览: 59
如果你想将字符出现概率统计结果保存到文件中,可以使用C++中的fstream库来写入文件。具体实现如下:
```c++
#include <iostream>
#include <fstream>
#include <map>
#include <string>
using namespace std;
int main() {
ifstream fin("filename.txt");
if (!fin.is_open()) {
cout << "Failed to open the file!" << endl;
return 0;
}
map<char, int> mp;
char ch;
while (fin.get(ch)) {
mp[ch]++;
}
fin.close();
ofstream fout("result.txt");
if (!fout.is_open()) {
cout << "Failed to create the result file!" << endl;
return 0;
}
for (auto it = mp.begin(); it != mp.end(); it++) {
fout << it->first << ": " << it->second << endl;
}
fout.close();
return 0;
}
```
这段代码中,我们首先使用ifstream库打开文件并进行字符出现概率统计,然后使用ofstream库创建一个新的文件,并将统计结果写入其中。需要注意的是,在使用ofstream库写入文件时,需要判断文件是否成功创建,否则可能会出现写入失败的情况。
阅读全文
相关推荐















