如何检查字母表中的字母在文本文件中出现了多少次 C++

How to check how many times the letters of the alphabet occur in a text file C++

我想检查字母表中的字母在文本文件中出现了多少次。

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

using namespace std;


int main()
{
char alphabet[]="abcdefghijklmnopqrstuvwxyz";
//char alphabet[26]= {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int letter_c[26]; //will contain the times each letter is repeated
string line;

//get text file
ifstream myfile ("hi.txt");

//if file opens...
  if (myfile.is_open())
  {
     while ( getline (myfile,line) )
     {  
         cout << line << '\n';

          //lowercase everything
          for (int i = 0; i < line.length(); i++)
          {
              line[i] = tolower(line[i]);
          }  

          //check if letter ? is in that text file and how many times
          for (int i = 0; i < line.length(); i++)
          {
               int count=0;
               for(int j=0; j<strlen(alphabet);i++)
               {
                   if(line[i]==alphabet[j])
                   {
                      cout<<"letter: alphabet "<<alphabet[j]<<endl;
                      cout<<"letter: text "<<line[i]<<endl;
                      letter_c[i]=count++;
                      //cout<<count<<endl;
                    }
               cout<<alphabet[i]<<" "<<letter_c[i]<<endl;
           }
      }
 }

//close file
myfile.close();
  }

  //file not found
  else cout << "Unable to open file"; 

return 0;

}

我相信这个 if 语句是我的代码乱七八糟的原因:

if(line[i]==alphabet[j])
{
cout<<"letter: alphabet "<<alphabet[j]<<endl;
cout<<"letter: text "<<line[i]<<endl;
letter_c[i]=count++;
//cout<<count<<endl;
}

我试过使用 line[i].compare(alphabet[j]) == 0 我也试过 strcmp (line[i],alphabet[j]) == 0 而且它们都不起作用。

你想要std::map。你的钥匙是字母,你的价值是计数。

像这样应该可以满足您的要求:

std::map<char, unsigned int> count;

std::fstream file("foo.txt");
char letter;

while(file >> letter)
{
    count[c] += 1;
}

如果要将大写字母和小写字母视为相同,则使用std::tolower:

count[std::tolower(c)] += 1;

这还有计算标点符号和特殊字符的额外好处。

你把逻辑复杂化了,而只是在找到的字母索引处增加 letter_c 中的计数,如下所示:

int letter_c[26] = {0};
while ( myfile >> c )
{
    if( isalpha(c) )
    {
        ++letter_c[ tolower(c) - 'a' ] ; // Change to lower case, subtract ascii of a
    }
}