簡體   English   中英

計算C ++文本文件中特定單詞的出現次數

[英]Count number of appearances of a specific word in a C++ text file

我分配給班級來編寫代碼,該代碼將計算不區分大小寫.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();

我的猜測是,不計算在內的8個單詞的末尾都有換行符,即它們出現在文件的行尾。 你能檢查一下是不是這種情況? 根據http://www.cplusplus.com/reference/string/string/operator%3E%3E/ ,>>運算符使用空格作為分隔符進行解析。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM