gpt4 book ai didi

c++ - C++计算文件中某个单词出现的次数

转载 作者:行者123 更新时间:2023-11-28 02:24:22 25 4
gpt4 key购买 nike

这是我的代码,用于计算文件中特定字符串的出现次数。

#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

关于c++ - C++计算文件中某个单词出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31236443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com