C++ 如何检查字母表中的字母在文本文件C+中出现的次数+;

C++ 如何检查字母表中的字母在文本文件C+中出现的次数+;,c++,string,char,text-files,alphabet,C++,String,Char,Text Files,Alphabet,我想检查一个文本文件中的字母有多少次 #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'

我想检查一个文本文件中的字母有多少次

#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;

}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符字母[]=“abcdefghijklmnopqrstuvwxyz”;
//字符字母[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];//将包含每个字母的重复次数
弦线;
//获取文本文件
ifstream myfile(“hi.txt”);
//如果文件打开。。。
如果(myfile.is_open())
{
while(getline(myfile,line))
{  
你想要的。你的钥匙是字母,你的价值是计数

像这样的东西可以满足您的需求:

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

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

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

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

您的逻辑过于复杂,只需在找到的字母索引处增加字母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
    }
}

不需要缓存字母表,只需使用
(字母-'a')
——其中
字母
字符
。不需要小写,只需使用if语句
if(大写)(字母-'a'))
,甚至可以用三元数简化。说真的,这可以用4行或5行程序编写,使用
std::map
@PaulMcKenzie,正如我的回答所示,但是如果你不知道
std::map
存在,那么你就想不起来了(除非你自己重新实现它)是的,很难制作一个比这个更干净的版本。虽然它肯定比普通的旧数组占用更多的内存。@sircodesalot确实,你可以使用一个数组并抵消这些值。但是,对于大多数人来说,这已经足够了。
count[std::tolower(c)] += 1;
int letter_c[26] = {0};
while ( myfile >> c )
{
    if( isalpha(c) )
    {
        ++letter_c[ tolower(c) - 'a' ] ; // Change to lower case, subtract ascii of a
    }
}