从计数错误的文件中读取数据。读取数据的最佳做法是什么?

Reading data from a file with wrong count. What's best practice for reading in data?

本文关键字:数据 读取 最佳 是什么 文件 错误      更新时间:2023-10-16

我有四组文本文件,每组都包含不同的单词。

noun.txt有7个单词Article.txt有5个字verb.txt有6个单词Preposition.txt有5个单词

在下面的代码中,在我的第二个for循环中,一个计数数组跟踪我在哪个文件中读取了多少单词。例如。count[0]应该是5个世界,但count[1]有8个单词,但应该是7个。我回去查看了文本文件,没有出错,它有7个单词。这是ifstream的行为问题吗?

我也被告知()不是一个好的做法。在准确读取数据方面,行业中的最佳实践是什么?换句话说,除此之外,还有什么更好的东西可以用吗!infile.of()?

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cctype>
#include <array> // std::array
using namespace std;
const int MAX_WORDS = 100;
class Cwords{
    public:
        std::array<string,4> partsOfSpeech;
};
int main()
{
    Cwords elements[MAX_WORDS];
   int count[4] = {0,0,0,0};
   ifstream infile;
    string file[4] = {"Article.txt",
                      "Noun.txt",
                      "Preposition.txt",
                      "verb.txt"};
    for(int i = 0; i < 4; i++){
        infile.open(file[i]);
        if(!infile.is_open()){
            cout << "ERROR: Unable to open file!n";
            system("PAUSE");
            exit(1);
        }
        for(int j = 0;!infile.eof();j++){
            infile >> elements[j].partsOfSpeech[i];
            count[i]++;
        }
        infile.close();
    }
    ofstream outfile;
    outfile.open("paper.txt");
    if(!outfile.is_open()){
        cout << "ERROR: Unable to open or create file.n";
        system("PAUSE");
        exit(1);
    }

    outfile.close();
    system("PAUSE");
    return 0;
}

正确读取数据的简单答案是:始终在读取后测试读取操作是否成功。本测试不涉及使用eof()(任何在阅读前教授使用eof()的书籍都值得立即烧掉)。

读取文件的主循环应该是这样的:

for (int j = 0; infile >> elements[j].partsOfSpeach[i]; ++j){
    ++count[i];
}

顺便说一句,尽管该语言被称为"C++"而不是"++C",但除非你真的使用了表达式的结果,否则不要使用后增量:在大多数情况下,这并不重要,但有时确实重要,然后后增量可能比前增量慢得多。

您是否检查过以确保文本文件末尾没有任何额外的空格或换行符?您的最后一个多余"单词"可能是由于到达eof之前的尾随字符造成的。

文件末尾可能有一行空行,看起来是"空的"。我的建议是使用如下代码:

#include <boost/algorithm/string.hpp>
#include <string>
...
    std::string line;
    int cnt = 0;
    while(! infile.eof()) {
        infile >> line;
        boost::algorithm::trim(line);
        if(line.size > 0)
            words[filenr][cnt++] = line;
    }

请注意,我强烈建议使用一个"外部"对象,它按列表类型进行索引(如Article.txt为0,Noun.txt为1),而"内部"对象是一个向量,它接受单词。您的实现是相反的,这是次优的,因为您必须在实现中的partsOfSpeech向量中携带空槽。还要注意,在您的示例中,为每个文件的字数设置"100"的硬上限是非常危险的——这可能会导致缓冲区溢出!对于实际的单词列表,最好使用std::vector,因为vector很容易自动扩展。