[英]Counting word occurence in textfile
這是我基於此處的代碼http://www.thecrazyprogrammer.com/2015/02/c-program-count-occurrence-word-text-file.html 。 (C++ 中的新功能)
#include <iostream>
#include <fstream>
#include<cstring>
using namespace std;
int main()
{
// std::cout << "Hello World!" << std::endl;
// return 0;
ifstream fin("my_data.txt"); //opening text file
int count=0;
char ch[20],c[20];
cout<<"Enter a word to count:";
gets(c);
while(fin)
{
fin>>ch;
if(strcmp(ch,c)==0)
count++;
}
cout<<"Occurrence="<<count<<"n";
fin.close(); //closing file
return 0;
}
模式計數錯誤
my_data.txt 中只有 3 個“世界”,但是當我運行程序時,結果為
這是文本文件的內容
使用 std::string 的解決方案
int count = 0;
std::string word_to_find, word_inside_file;
std::ifstream fin("my_data.txt");
std::cout << "Enter a word to count:";
std::cin >> word_to_find;
while (fin >> word_inside_file) {
if (word_to_find == word_inside_file )
count++;
}
std::cout << "Occurrence=" << count << "";
如果您還想在其他字符串中查找所有匹配項,如注釋中所述,您可以執行以下操作:
...
while (fin >> word_inside_file) {
count += findAllOccurrences(word_to_find, word_inside_file);
}
...
在findAllOccurrences(std::string, std::string)
您將實現“查找另一個字符串中出現的所有字符串”算法。
如果您是 C++ 新手,您不應該真正使用 get。 閱讀“緩沖區溢出漏洞”。 get() 更像 c 風格。 您應該考慮使用 std::cin。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.