微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

排序数组/文件I / O C.

我想知道是否有人可以帮助我排除这个数组,我对如何在这个项目中完全实现它感到很遗憾.因为它是HW并没有透露整个答案,而是将我推向正确的方向.该项目如下:
编写一个程序,该程序将读取一行文本并输出文本中出现的所有字母的列表以及每个字母出现在该行中的次数.以一个作为标记值的句点结束该行.这些字母应按以下顺序使用:从最高到最低.假设输入使用全部小写字母.
几个问题.
1.我是否正确地对阵列进行排序?
2.在将排序数组放入我的代码之前,当代码编译时,它会出现一个空白屏幕.有什么办法解决这个问题?

如果写得不好而道歉,并提前感谢您的帮助!

inlcude <iostream>
#inlcude <fstream>
using namespace std;
void initialize(int list[]);
void Sort(int list[],int& num);
void characterCount(char ch,int list[]);
void readText(ifstream& intext,char& ch,int list[]);
void totalCount(int list[]);
int main()
{
int index,letterCount[26];
char ch;
ifstream inFile;

infile.open("C:/temp/Data_Chapter_7_8.txt");

if (!inFile)
{
   cout << " Cannot open file." <<endl;
}
initialize(letterCount);
infile.get(ch);

while (inFile)
{
  int index;
  readText(inFile,ch,letterCount)
  index++;
  inFile.get(ch);
  }
  totalCount(index,letterCount);

  inFile.close();

  system("PAUSE");
  return 0;
  }
  //initializes array letterCount to 0
  void initialize(int list[])
  {
 for(int x = 0;x<26;x++)
 list[x] = 0
 }
 //increments the letter count. Makes sure counting letters.
 void characterCount (char ch,int list[])
 {
 int index;
 ch = tolower(ch);
 if(static_cast<int>(ch)>=97&&(static_cast<int>(ch)<=122))
  letterCount[static_cast<int>(ch)-97]++;  
  }
  void readText(ifstream& intext,int list[])
  { 
  while (ch != '.')
  {
  characterCount (ch,list);
  intext.get(ch);
  }
  }
  //displays data
  void totalCount(int list[])
  {
 for(int x=0;x<26;x++)
 if(letterCount[x]>0)  
 cout<<static_cast<char>(x+97)<<" "<<letterCount[x]<<endl;
 }
 void Sort(int list[],int& num)
      {
 int i,j,flag = 1;
 int temp;
 int numLength = num.length();
 for (i=1;(i<=numLength)&&flag; i++)
 {
     flag = 0;
     for (j=o; j<(numLength-1);j++0
     {
         if(num[j+1]>num[j])
         {
             temp = num[j];
             num[j] = num[j+1];
             num[j+1]=temp;
             flag = 1;
         }
     }
 }
             return;
             }

解决方法

我们可以简单地跟踪每个字母的出现次数,而不是使用凌乱的泡泡排序和其他有趣的东西,因为只有26种可能性.这应该会导致更清晰(更快)的代码

int numOccur[26];
...
for (int i = 0; i < numCh; i ++)
    numOccur[letters[i] - 'a'] ++;
for (i = 25; i >= 0; i --)
    if (i > 0)
        cout<<static_cast<char>(i+97)<<" "<<numOccur[i]<<endl;

当然,您应该使用适当的文件读取循环替换for循环.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐