用C++计算一个单词在文件中的出现次数
Counting the occurances of a word in a file in C++
这是我的代码,用于统计文件中特定字符串的出现次数。
#include <iostream>
#include <string>
int frequency(std::string s, std::string file_name){
std::ifstream file;
std::string word;
int count = 0;
try{
file.open(file_name);
while(file>>word){
if(s.compare(word) == 0) ++count;
}
file.close();
}catch(std::ifstream::failure e){
//std::cout<<e<<std::endl;
}
return count;
}
//===============================================
int main() {
std::string file_name, word;
std::cout << "Enter file name.." << 'n';
std::cout << "Enter word.. " << 'n';
std::cin >> file_name >> word;
int count = frequency(word, file_name);
std::cout << "Occurrences of " << word << ": " << count;
return 0;
}
该文件在项目的根目录中提供。问题是,对于任何正在计数的单词,我都会得到0
。
我从file.open(file_name);
更改为file.open(file_name.c_str())
;而且效果很好。
$ cat file.txt
hello
good bye
$ a.out
Enter file name..
Enter word..
file.txt
hello
Occurances of hello: 1
ifstream
将c字符串作为输入,而不是字符串。要捕获,请确保文件在读取之前已打开:
if (file.is_open()){
... do stuff....
else
... error
通过一些小的更正,您的代码就可以完成这项工作,特别是文件读取循环可以被修改为首先读取整行,然后分别读取其中包含的每个string
:
int frequency(std::string s, std::string file_name) {
std::ifstream file(file_name.c_str());
// check if file successfully open
if (!file) cerr << "Can't open input file!n";
int count = 0;
try{
// extract all lines
std::string line;
while(getline(file, line)) {
stringstream ss(line);
string word;
// extract all words separated by white space
while (ss >> word) {
// compare with wanted
if(s == word) ++count;
}
}
}catch(std::exception& e){
// std::cout << e.what() << std::endl;
}
return count;
}
注意事项:
您不需要显式关闭文件流,这是在最后自动完成的,因为
file
是函数中的局部变量。如果仅使用
try
-catch
块来检查流状态,则该块是冗余的。正如答案中所指出的,你可以用一行字来完成。文件名最好是c风格的字符串(以"\0"结尾(。流成员函数
c_str()
执行转换。您可以在流的定义中打开文件,并跳过包含流成员函数
open()
的行。
相关文章:
- 文本文件中的单词链表
- 在指针的帮助下,文本文件中单词的频率
- 我们如何在文本文件中找到C++中的几个单词?
- 是否可以在文本文件中找到最长单词的长度,并在同一个文本文件中读取,只需 1 个 while 循环?
- 按单词搜索文件,然后在C++中打印特定行数
- 如何检查流中文件的下一个单词是否为 alpha?
- 从文件中查找单词并替换到其他文件中
- 该程序将.csv文件中的一系列单词放入数组中,然后随机生成句子.但它不起作用
- 如何逐行从文件中获取单词,并在C++中用分号分隔?
- 如何从文件中读取单词,将它们分配给数组并分析其内容?
- 如何在 c++ 中从文本文件中获取特定单词?
- 我们如何重新制作程序以打开xml文件并在价格单词之后读取百分比值并更改此值
- 从之前添加的批处理文件中删除单词
- C++读取大文件并将其保存到字符串中,然后删除特定的随机单词
- C++ 如何检查哪些单词不在 2 个类似文件中
- 显示文件中具有最小给定元音数的单词
- 简单的二分搜索对我不起作用。我正在尝试从文本文件中搜索单词
- 使用结构数组计算文本文件中单词的出现次数C++
- 包含换行符分隔的单词的文件和C++中这些单词的字符串向量的大小是否相同?
- 将文本文件单词插入 AVL