我想检查字母表中的字母在文本文件中的次数。
#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 他们都没有工作。
答案 0 :(得分:3)
你过度使逻辑变得复杂,而只是在找到的字母索引处增加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
}
}
答案 1 :(得分:2)
你想要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;
这还有计算标点符号和特殊字符的额外好处。