计算C ++文本文件中特定单词的出现次数

时间:2017-02-10 22:43:06

标签: c++ string count

我已经为课程编写了一个代码,用于计算.txt文件中特定单词的出现次数不区分大小写

int main(){
    char U[50];
    string a;
    int number=0;
    cout<<"name of file"<<endl;
    cin.getline(U,50);
    ifstream text(U,ios_base::binary);
    if(!text){
        cout<<"nonexisting"<<endl;
        return 0;
    }
    cin>>a;
    transform(a.begin(), a.end(), a.begin(), ::tolower);
    string word;
    while(text>>word){
        transform(word.begin(), word.end(), word.begin(), ::tolower);
        if(!a.compare(word))number++;       
    }
    cout<<number;
    text.close();
    return 0;
}

问题是程序在文件中计数32个字,但其中有40个

这是我解决问题的方法

int main(){
char U[50];
string a;
int number=0;
cout<<"name of file"<<endl;

cin.getline(U,50);
ifstream text(U);
if(!text){
cout<<"nonexisting"<<endl;
return 0;
}

cin>>a;

transform(a.begin(), a.end(), a.begin(), ::tolower);
string word;
while(text>>word){
    transform(word.begin(), word.end(), word.begin(), ::tolower);
    if (word.find(a) != string::npos)number++;

}   
cout<<number;
text.close();

1 个答案:

答案 0 :(得分:0)

我的猜测是,未计算的8个单词在结尾处有一个换行符,即它们出现在文件的行尾。你能检查一下是否是这种情况?根据{{​​3}},&gt;&gt;运算符使用空格作为分隔符进行解析。

相关问题