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

标签 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','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 但它们都不起作用。

最佳答案

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

关于c++ - 如何检查字母表中的字母在文本文件中出现了多少次 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28095819/

相关文章:

c++ - 如何在完美转发中有效地将右值引用转为左值

c++ - 如何将 char 数组元素传递给 C++ 中的函数?

C++ 不在任务栏中显示使用 CreateWindow 创建的窗口

c++ - 将手写循环转换为标准库调用

c++ - 在模板类之外的容器类型上编写模板化成员函数

java - 想要删除前面的星号和字符并跟随它,为什么我的代码不起作用

string - 为什么看似空的文件和字符串会产生 md5sum?

java - 如何在Android Studio中启用String.xml中的状态栏,我突然点击了隐藏通知

c# - 如何检查字符串的最后一个字符并查看它的空格

objective-c - 如何在不实际更改的情况下重新排列 char* 的开头和结尾(索引方式)?