c ++,我正在制作一个程序来计算一个字母出现在文件中的时间

时间:2018-05-14 21:17:35

标签: c++ file

应该指出,我们也在检查涉及该字母的最长字以及最短字。

应该说我是学生,我的代码有一些错误

警告:缺乏评论也应该说明,由于老师给出的模糊指示,我不知道我在做什么 我的代码; word.cpp

#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>
#include<iomanip>
#include"myStrCharFunc.h"
using namespace std;

const int SIZE=26; //Size of the area, one for each letter
const int MAX=30; //Size of the c string that will store word from the input file

typedef char cstr[MAX];

struct let
 {
   int count;//nummber of words that start with thr letter
   int shortest;
   int longest;
 };

void initializeArray(let ar[]);
void readData(let ar[]);
void processWord(cstr word, let ar[]);

int main()
 {
   //cstr s="Hi";
   let ar[SIZE];

   return 0;
 }

void initializeArray(let ar[])
 {
   for(int i=0;i<SIZE; i++)
    {
      ar[i].count=0;
      ar[i].shortest=9999;
      ar[i].longest=0;
    }
 }

void readData(let ar[])
 {
  ifstream fin;
  fin.open("project2.dat");
  if(!fin)
   {
     cout<<"Your input file doesn't exist"<<endl;
   }
  else
   {

     //let temp;
     //fin>>temp.count;
     //fin>>temp.shortest;
     //fin>>temp.longest;
     cstr word=" ";
     fin>>word;
     while(fin)
      {
        processWord(word, ar);
        fin>>word;
      }
   }
 fin.close();
}

void processWord(cstr word, let ar[])
 {

  for(int i=0; i < SIZE; i++)
   {
    ar[i].count++;
    myToUpper(word);
    int fev = myStrLen(word);
    if(ar[i].longest < fev)
      {
        ar[i].longest = fev;
      }
    if(ar[i].shortest > fev)
     }
       ar[i].shortest=fev;
     }

}

与此相关的其他程序; myStrCharFunc.h

 //myToUpper('a')-->'A'
//myToUpper('A')-->'A'
char myToUpper(char b)
 {

   if('a'<= b && b <= 'z')
    {
      b-=('a'-'A');
    }
   return b;
 }

int myStrLen(const char cstr[])
 {
  int i=0;
  for(i; cstr[i] != '\0'; i++)
    ;
  return i;

 }

myToUpper假设接受一个字符或C-String并使用ASCII表使其成为大写字母

与此同时,myStrLen假设记录了每个单词的长度。

我写的代码的错误是:

  

word.cpp:在函数'void processWord(char *,let *)'中:word.cpp:77:21:   错误:从'char *'到'char'的无效转换[-fpermissive]

   myToUpper(word);
                 ^ In file included from word.cpp:6:0:  myStrCharFunc.h:3:6: error:   initializing argument 1 of ‘char
     

myToUpper(char)'[-fpermissive] char myToUpper(char b)

/ 应该说明,在按下CTRL + K并在给定区域中剪切并粘贴它之后,我在这里编写的代码都没有正确格式化,所以这一切都是手工完成的 / < / p>

我们正在使用的文件; project2.dat仅包含:

Economists attributed the jump in tourism to a strengthening
economy high consumer confidence and pent up demand among
Americans who put off travel during the recession Also
a growing middle class in China is pushing visits from that
country experts said

The state persistent drought although weighing heavily on
residents does not appear to bother travelers interested in
sunshine shopping and sightseeing

Visitors to Los Angeles are not going to care if it gets a
little brown around the edges quipped Dean Runyan a
consultant who studied the tourism economy for Visit
California report released Tuesday

Still Runyan cautioned the drought could affect tourism
in rural counties where fishing and boating are popular pastimes

Some experts worry that a bigger issue is the US dollar
strength compared to other currencies

2 个答案:

答案 0 :(得分:2)

我不知道你是否能够为你的项目/任务使用STL结构(如果没有,我为一个坏教练道歉),所以如果没有,那么这将是为了任何访问者的利益谁想要一个/理智/方法来解决这个问题,因为STL的轻量化让这非常简单:

#include<fstream>
#include<iostream>
#include<map>
#include<string>
#include<cctype>

int main() {
    //Container for the frequency data
    std::map<char, size_t> char_map;

    //Read the whole file into memory, for efficient reads
    std::string file_contents;
    std::ifstream file("project2.dat");
    size_t length;
    file.seekg(0, std::ios::end);
    length = file.tellg();
    file.seekg(0, std::ios::beg);
    file_contents.resize(length);
    file.read(file_contents.data(), length);
    //If you don't have a C++17 compiler, use this instead:
    //file.read(&file_contents.front(), length);

    //Iterate over the file, which we've stored in memory.
    for(char c : file_contents)
        //Omit if we're including spaces
        if(c != ' ')
            ++char_map[char(std::toupper(c))];

    //Display the results
    for(auto const& pair : char_map) {
        std::cout << "Occurrences of \'" << pair.first << "\': " << pair.second << '\n';
    }
}

注意:此方法仅适用于单字节文本编码。对于任何多字节文本编码都不安全。

此程序的输出将是按字典顺序排列的文件中每个字符的频率,不区分大小写。

//Input:
I watched as nobody attended my fourth grade birthday party.

//Output:
Occurrences of '.': 1
Occurrences of 'A': 6
Occurrences of 'B': 2
Occurrences of 'C': 1
Occurrences of 'D': 6
Occurrences of 'E': 4
Occurrences of 'F': 1
Occurrences of 'G': 1
Occurrences of 'H': 3
Occurrences of 'I': 2
Occurrences of 'M': 1
Occurrences of 'N': 2
Occurrences of 'O': 3
Occurrences of 'P': 1
Occurrences of 'R': 4
Occurrences of 'S': 1
Occurrences of 'T': 6
Occurrences of 'U': 1
Occurrences of 'W': 1
Occurrences of 'Y': 4

如果我们从标准输入中读取它会更简单。这个/可以/适用于文件,但它可能比我上面使用的方法慢,特别是大文件。

#include<iostream>
#include<map>
#include<string>
#include<cctype>

int main() {
    std::map<char, size_t> char_map;
    std::string line;

    while(std::getline(std::cin, line))
        for(char c : line)
            if(c != ' ')
                ++char_map[char(std::toupper(c))];

    for(auto const& pair : char_map) {
        std::cout << "Occurrences of \'" << pair.first << "\': " << pair.second << '\n';
    }
}

答案 1 :(得分:0)

假设你还没有用C ++覆盖容器

所以你想要计算你阅读的文件中的字母频率。

现在你唯一需要的是一个可以表示所有字母的数组。

int freq[MAXCHARS] = {0};  // e.g. 26

假设我们使用ASCII字符,则从ASCII值65开始,这是&#39; A&#39;

在C ++数组中从索引0开始,所以你需要一种方法将字符映射到数组&#39; freq&#39;

通过减去A&#39;来计算指数。然后,根据角色,您将获得&#39; A&#39;的索引0,以及&#39; B&#39;等

文本可能是混合大小写,因此使用函数toupper()

将所有内容转换为大写
ch = std::toupper(ch);  // make sure it is upper case
auto index = ch - 'A';  // calculate the index in the array
freq[index]++;          // add one for the character found

现在您需要做的是一次从文件中读取一个字符,并确定它是否是一个字母 如果是,则更新数组

#include <iostream>
#include <string>
#include <fstream>
#include <cctype>

const int MAXCHARS = 26;

int main(/*int argc, char* argv[]*/)
{
  using namespace std;

  int freq[MAXCHARS] = {0};

  std::ifstream f("yourfile");
  do
  {
    auto ch = f.get();
    if (std::isalpha(ch))
    {
      ch = std::toupper(ch);
      auto index = ch - 'A';
      freq[index]++;
    }
  }
  while (!f.eof());

  for (int i = 0; i < MAXCHARS; ++i)
  {
    std::cout << char(65+i) << ":" << freq[i] << '\n';
  }
  std::cout << std::endl;    

  return 0;
}