我正在编写一个程序,该程序应打印数据文件中每个字母的使用情况。数据文件如下所示:“您好,世界一切都很棒。您好,世界一切都很棒。您好,我的世界也很棒。”如果运行该程序,它将从A-z(65-122)打印出ASCI表中的每个字符,并打印出它的出现。我的问题是,有没有办法打印出数据文件中使用的唯一字符及其出现的内容?这是我的代码:
#include "stdafx.h"
#include<iostream>
#include <fstream>
#include <string>
using namespace std;
const int SIZE = 128;
void storeFunction(int store[]);
void storeFunction(int store[])
{
ifstream in; //declares input file
in.open("mytext.dat"); //reading file
char Check; //declaration to read each character in the file
if (in.fail())
{
cout << "Text did not open correctly." << endl;
}
else
{
while (!in.eof()) {
in >> Check; //saving each single character in Check
store[Check]++; //this loop will find each letter, with the ASCI table, and store it in Check.
}
for (int i = 'A'; i < 'z'; i++)
{
cout << "Character: "<< char(i) << " Frequency: " << store[i] << endl;
}
}
in.close();
}
int main()
{
int store[SIZE] = { 0 }; //setting the initializer list to 0.
storeFunction(store); //call the function
return 0;
}
谢谢。
答案 0 :(得分:-3)
#include<iostream>
#include <fstream>
#include <string>
#include <unordered_map>
using namespace std;
void printCharOccurance();
void printCharOccurance()
{
ifstream in; //declares input file
in.open("mytext.dat"); //reading file
char readChar;
if (in.fail())
{
cout << "Failed to open the file" << endl;
}
else
{
unordered_map<char,int> storeCharacterOccurance;
while (!in.eof()) {
in >> readChar; //saving each single character in readChar
if(!(((readChar >='a') && (readChar <='z')) || ((readChar >='A') && (readChar <='Z'))))
continue;
storeCharacterOccurance[readChar]++; //this loop will iterate over each character in file if character is a-z or A-Z
}
for (auto& x: mymap) {
cout << "Character: "<< x.first << " Frequency: " << x.second << endl;
}
}
in.close();
}
int main()
{
printCharOccurance(); //call the function
return 0;
}