C++ 无法读取 txt 文件中的单词
C++ Cannot read words from a txt file
我目前正在尝试编写一个可以从文本文件中读取单词的程序。最后,我计划从文件中读取某些单词等等,但目前我无法让我当前的代码工作。
我有 3 个文件。头文件、主文件和实现文件。
读字.h
#ifndef READWORDS_H
#define READWORDS_H
/**
* ReadWords class. Provides mechanisms to read a text file, and return
* capitalized words from that file.
*/
using namespace std;
#include <string>
#include <fstream>
class ReadWords
{
public:
/**
* Constructor. Opens the file with the default name "text.txt".
* Program exits with an error message if the file does not exist.
*/
ReadWords();
/**
* Constructor. Opens the file with the given filename.
* Program exits with an error message if the file does not exist.
* @param filename - a C string naming the file to read.
*/
ReadWords(char *filename);
/**
* Closes the file.
*/
void close();
// working storage.
private:
string nextword;
ifstream wordfile;
bool eoffound;
};
#endif
读字.cpp
#include "ReadWords.h"
#include <iostream>
using namespace std;
//:: Defines function as member of class.
ReadWords::ReadWords(char *filename)
{
ifstream str;
str.open("hamlet.txt");
char c;
while ((c = str.get()) !=EOF){
cout << c << endl;
}
}
void close()
{
}
主.cpp
#include "ReadWords.h"
int main()
{
ReadWords rw;
rw.ReadWords("hamlet.txt");
}
现在我知道我显然做错了什么,但我不是100%确定是什么。 我在编译中收到的错误如下:
main.cpp: In function `int main()':
main.cpp:6: error: invalid use of `class ReadWords'
工具已完成,退出代码为 1
任何帮助都非常感谢。 :)
在你的主.cpp中,你错过了#include ReadWords.h
指令中的引号。要解决此问题,您应该使用#include "ReadWords.h"
.
另外,您应该注意,std::istream::get
只返回一个字符。如果你想在(例如)std::string
中阅读整个单词,你应该使用这样的std::istream::operator >>
:
std::ifstream in("my_file");
std::string word;
if (in.is_open()) {
while (in >> word) {
//do something with word
}
}
另一件突出的事情是,在rw.ReadWords("hamlet.txt")
中,您调用构造函数就好像它是成员函数一样。使用该重载的正确方法是:ReadWords rw("hamlet.txt")
。
作为旁注:构造函数的工作是初始化对象。在身体内部做更多的事情不是一个好习惯。
修复编译器的第一个错误,main的第一行.cpp
#include ReadWords.h
需要:
#include "ReadWords.h"
它应该是
#include "ReadWords.h"
或
#include <ReadWords.h>
首先,你需要在 rw 之后添加一个 ";"。ReadWords("hamlet.txt") in main.cpp.这就是编译器输出的最后一行的含义。
这似乎不必要地复杂。这不行吗?
vector<string> words;
string word;
while(cin >> word)
words.push_back(word);
编程中有许多错误:
- 关闭已打开的文件。请始终记住这一点,它可能会导致运行时错误。
- 在主文件中.cpp第一行 #include"ReadWords.h">
- 在代码行的末尾放一个分号:rw。读字("哈姆雷特.txt");
相关文章:
- 文本文件中的单词链表
- 在指针的帮助下,文本文件中单词的频率
- 我们如何在文本文件中找到C++中的几个单词?
- 是否可以在文本文件中找到最长单词的长度,并在同一个文本文件中读取,只需 1 个 while 循环?
- 按单词搜索文件,然后在C++中打印特定行数
- 如何检查流中文件的下一个单词是否为 alpha?
- 从文件中查找单词并替换到其他文件中
- 该程序将.csv文件中的一系列单词放入数组中,然后随机生成句子.但它不起作用
- 如何逐行从文件中获取单词,并在C++中用分号分隔?
- 如何从文件中读取单词,将它们分配给数组并分析其内容?
- 如何在 c++ 中从文本文件中获取特定单词?
- 我们如何重新制作程序以打开xml文件并在价格单词之后读取百分比值并更改此值
- 从之前添加的批处理文件中删除单词
- C++读取大文件并将其保存到字符串中,然后删除特定的随机单词
- C++ 如何检查哪些单词不在 2 个类似文件中
- 显示文件中具有最小给定元音数的单词
- 简单的二分搜索对我不起作用。我正在尝试从文本文件中搜索单词
- 使用结构数组计算文本文件中单词的出现次数C++
- 包含换行符分隔的单词的文件和C++中这些单词的字符串向量的大小是否相同?
- 将玩家输入与单词文件进行比较