c++ - 文件for循环不打开文件c ++
问题描述
由于我真的不知道的原因,该文件没有打开,有什么见解吗?
#include <iostream>
#include <string>
#include <algorithm>
#include <fstream>
#include <cctype>
using namespace std;
.
.
.
.
.
void MinHeap::TopKFrequentWord(string fileName, int k)
{
MinHeap mh;
Trie T;
string word;
string line;
ifstream inFile(fileName);
for (int i = 0; i < 22; i++)
{
if (i >= 10)
{
fileName = "C:\\Users\\Kareem's Laptop\\Desktop\\Reuters-21578\\reut2-0" + to_string(i) + ".sgm";
}
else if (i <= 9)
{
fileName = "C:\\Users\\Kareem's Laptop\\Desktop\\Reuters-21578\\reut2-00" + to_string(i) + ".sgm";
}
if (!inFile)
{
cout << fileName << " did not open." << endl;
exit(1);
}
bool found = true;
while (inFile >> line)
{
size_t pos = line.find("<BODY>");
if (pos != string::npos)
{
if (found)
{
word = line.substr(pos + 6);
found = true;
TrieNode* TN = T.search(word);
if (!TN)
{
TN = T.insert(word);
}
else
{
TN->frequency++;
}
mh.insert(TN, word);
}
}
}
mh.Display();
cout << '\n';
inFile.close();
}
}
int main()
{
MinHeap foo;
string fileName;
foo.TopKFrequentWord(fileName, 10);
return 0;
}
我必须循环打开 21 个文件,全部阅读并打印出所有这些单词的前 10 个字数。由于指令,无法使用向量。如果相似之处很明显,我深表歉意。我尝试将所有文件放在一个数组中,但它仍然不起作用。没有错误只是没有打开(获取 exit(1) 命令)。
解决方案
您在循环之前打开文件。由于您正在更新filename
循环内的变量,我想您希望每次通过循环时都打开它。
移动线:
ifstream inFile(fileName);
到测试前一行:
if (!inFile)
此外,您编写代码的地方ifstream inFile(fileName);
有一个空字符串fileName
(您没有初始化在 main 中作为参数传递的变量)。
此外,您将 int k
参数传递给函数,但从不在那里使用它。
推荐阅读
- pip - 如何为通过 anaconda environment.yml 安装的 pip VCS 包指定源目录
- python - scrapy twisted.internet.error.ReactorNotRestartable
- c++ - 我的 C++ 文件需要一个“while”来代替 if。最后它期望一个'('
- powershell - Win10 Toast Notification 已暂停数据驻留在哪里?
- c# - UIAComWrapper 程序集在构建解决方案时抛出错误
- sql - 在同一个 .sql 文件中部署多个 SQL 作业
- google-apps-script - 如何获取/使用 2 个小部件的名称并在函数中使用它们?
- java - 解析模板 [users/list] 时出错,模板可能不存在或可能无法被任何已配置的模板解析器访问
- laravel - Laravel,从 php 调用 Artisan 与命令行不同
- wordpress - 如何仅获取所选子类别的帖子