簡體   English   中英

排序數組/文件I / O C ++

[英]Sorting Arrays/File 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, char& ch, 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循環。

只是幾條評論。

  1. 我認為這里的大部分演員都沒有任何充分的理由。
  2. 使用isalphaisupperislower來檢查字母,並使用tolowertoupper來對它們進行共同處理(注意:使用這些函數是少數幾種投射的理由之一)。
  3. 用`int lettercount [26] = {0}初始化你的lettercount數組可能最簡單;
  4. 除非您絕對需要編寫自己的排序例程,否則只需使用std::sort
  5. 在定義ifstream時,通常最容易打開文件: std::ifstream infile("whatever");
  6. 不要使用while (infile) 這幾乎是一個有保障的bug。 做一個閱讀,並檢查它是否成功,如: while (infile.get(ch)) ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM