【发布时间】:2016-04-08 02:59:33
【问题描述】:
我正在开发一个文本处理器,它从文件中获取文本并将其插入到 Graph 数据结构中。我制作了图表,但我在使用文本处理器时遇到了问题。每当我执行代码时,它都会说我无法打开文件。执行代码时,我确保文本文件位于同一目录中。下面是 GraphTextProcessor 类的代码:
#include <fstream>
#include <cstring>
#include <string>
#include "Graph.h"
class GraphTextProcessor {
private:
Graph* m_data;
public:
GraphTextProcessor();
Graph* process(std::string filename);
};
GraphTextProcessor::GraphTextProcessor() {
}
Graph* GraphTextProcessor::process(std::string filename) {
//process text file and insert into graph here
std::string word;
//opens file in read mode
std::ifstream readFile;
readFile.open(filename.c_str(), std::ios::in);
if (readFile.is_open()) { //Not opening
while (readFile >> word) {
std::cout << word << std::endl;
}
// Closes open text file
readFile.close();
}
else {
std::cout << "Unable to open text file." << std::endl;
}
return NULL;
}
我只是想先从文件中读取,然后再实际尝试写入图表。这是我在 Main 中运行的代码:
#include <iostream>
#include <string>
#include "GraphTextProcessor.h"
int main() {
GraphTextProcessor *gp = new GraphTextProcessor();
gp->process("hello.txt");
}
它打印"Unable to open text file"。有什么建议吗?
【问题讨论】:
-
您可能会发现让您的
"Unable to open..."打印filename和当前工作目录很有用,因为它将在其中查找文件。如果您从 IDE 运行程序,它可能不是您所期望的。