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

C++无法读取TXT文件中的单词,c++,file,class,text,readfile,C++,File,Class,Text,Readfile,我目前正试图编写一个程序,从文本文件中读取单词。最后,我计划从文件中读取某些单词等等,但目前我无法让当前代码正常工作 我有3个文件。头文件、主文件和实现文件 ReadWords.h #ifndef READWORDS_H #define READWORDS_H /** * ReadWords class. Provides mechanisms to read a text file, and return * capitalized words from that file. */ using

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

我有3个文件。头文件、主文件和实现文件

ReadWords.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
现在我知道我明显做错了什么,但我不能百分之百确定是什么。 我在编译中收到的错误如下:

main.cpp: In function `int main()':
main.cpp:6: error: invalid use of `class ReadWords'
工具已完成,退出代码为1


非常感谢您的帮助

要修复编译器的第一个错误,main.cpp的第一行

#include ReadWords.h
需要:

#include "ReadWords.h"
应该是

#include "ReadWords.h"


首先,您需要添加一个;在main.cpp中的rw.ReadWordshamlet.txt之后。这就是编译器输出的最后一行的含义。

这似乎不必要地复杂。这样不行吗

vector<string> words;
string word;
while(cin >> word)
    words.push_back(word);

在main.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.ReadWordshamlet.txt中,您调用的构造函数就像调用成员函数一样。使用该重载的正确方法是:ReadWords rwhamlet.txt


作为旁注:构造函数的工作是初始化对象。在它的身体里做更多的事情不是一个好的做法。

在你的编程中有很多错误:

关闭已打开的文件。请始终记住这一点,它可能会导致运行时错误。 在main.cpp文件的第一行包括ReadWords.h 在代码行末尾放一个分号:rw.ReadWordshamlet.txt;
始终查看您得到的第一个错误-包括预期的文件名或,并检查该行。如果你搜索Google,你会得到关于你做错了什么的几点提示…你用什么资源来学习C++?我会避免使用第二种形式的用户制作的头。可能有些情况下你可以使用它。首先,他需要重新阅读课本…或者基础教程非常感谢,不知道我怎么没有注意到这一点。如果从包含向量开始,将无法工作:-ifstream的析构函数将关闭文件。它不会导致任何运行时错误。
#include <ReadWords.h>
vector<string> words;
string word;
while(cin >> word)
    words.push_back(word);
std::ifstream in("my_file");
std::string word;

if (in.is_open()) {
    while (in >> word) {
        //do something with word
    }
}