首页 > 解决方案 > 文件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) 命令)。

标签: c++

解决方案


您在循环之前打开文件。由于您正在更新filename循环内的变量,我想您希望每次通过循环时都打开它。

移动线:

ifstream inFile(fileName);

到测试前一行:

if (!inFile)


此外,您编写代码的地方ifstream inFile(fileName);有一个空字符串fileName(您没有初始化在 main 中作为参数传递的变量)。

此外,您将 int k参数传递给函数,但从不在那里使用它。


推荐阅读