C++ 无法读取 txt 文件中的单词

C++ Cannot read words from a txt file

本文关键字:单词 文件 txt 读取 C++      更新时间:2023-10-16

我目前正在尝试编写一个可以从文本文件中读取单词的程序。最后,我计划从文件中读取某些单词等等,但目前我无法让我当前的代码工作。

我有 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);

编程中有许多错误:

  1. 关闭已打开的文件。请始终记住这一点,它可能会导致运行时错误。
  2. 在主文件中.cpp第一行 #include"ReadWords.h">
  3. 在代码行的末尾放一个分号:rw。读字("哈姆雷特.txt");