我想检查字母表中的字母在文本文件中出现了多少次。
#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/