在C++中使用ifstream打开文本文件时遇到问题
Having trouble opening a text file using ifstream in C++
我正在开发一个文本处理器,它从文件中接收文本并将其插入Graph数据结构中。我制作了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;
}
我只是想先从一个文件中读取,然后再真正尝试写入Graph。这是我在Main中运行的代码:
#include <iostream>
#include <string>
#include "GraphTextProcessor.h"
int main() {
GraphTextProcessor *gp = new GraphTextProcessor();
gp->process("hello.txt");
}
它打印"Unable to open text file"
。有什么建议吗?
我自己运行了代码,它运行得很好。列出你的编程环境以及你遵循了哪些步骤。请把你的问题做得更详细,并准确地解释你是如何做到的。
请确保以下内容:
- 请尝试使用完整的路径名称;例如
ifstream in("C:/someDirectory/andSomeOtherDirectory/one.txt");
- 请尝试更改文件的拼写
例如:
"One.txt"
或
"ONE.txt"
-
您需要获得读取该文件的权限。尝试更改文件的权限。
-
尝试不同的编译器
-
此外,如果您使用异常处理(try、throw、catch)而不是if,否则将有助于查找错误。
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何使用 c++ 实现并发文件/文本编辑?
- 我需要转换一些代码,以便它适用于输入和输出文件文本
- 通过套接字发送二进制文件.文本文件有效,其他文件无效
- 将大型数据文件拆分为多个小文件(文本格式)
- 如何读取输入文件(文本文件)并将输入验证为有效整数
- 从文本文件/文本流中读取Q字符串错误
- 从文本文件(文本解析器)C++中读取行和列的逻辑
- 如何将*.css文件(文本文件)的内容与附加信息存储在新文件中?
- 关于内存映射文件和使用大文件文本编辑器
- 如何在读取文件文本时跳过"n"
- 使用libzip从.zip获取文件(文本除外)