换行符后文件停止读取

时间:2014-09-25 17:39:53

标签: c++ file newline

我正在尝试创建垃圾邮件过滤器。我需要先训练模型。我从一个文本文件中读到了单词" spam"或"火腿"作为一个段落的第一个单词,然后是邮件中的单词和它出现的单词后面的单词。文件中有段落。我的程序能够读取第一段,即单词及其出现次数。

问题是,文件在遇到换行符后停止读取,并且没有读取下一段。虽然我觉得我检查作为段落结尾的换行符的方式并不完全正确。

我已经给出了两个段落,因此您只需了解火车文本。 训练文本文件。

/ 000/003 ham 需要1 fw 1 35 2 39 1感谢1个帖子2 40 1个拷贝1个1个1个相关器1个公司1个25 1他2 26 2 168 1 29 2内容4 1 1 6 1 5 1 4 1评论2我们1约翰3 17 1使用1 15 1 20 1类1可能1 a 1返回1 l 1 01 1生产1 i 1是1 10 2 713 2 v6 1 p 1原件2

/ 000/031 ham don 1 kim 5 dave 1 39 1 customer 1 38 2 thanks 1 over 1 thread 2 year 1 correlator 1 under 1 williams 1月2号2号厨房1 168 1 29 1内容4 3 2 2 6系统2 1 2 7 1 6 1 5 2 4 1 9 1每1 8 1视图2

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    int V = 0; // Total number of words

    ifstream fin;
    fin.open("train", ios::in);
    string word;
    int wordnum;
    int N[2] = {0};
    char c, skip;
    for (int i = 0; i < 8; i++) fin >> skip; // There are 8 characters before the first word of the paragraph
    while (!fin.fail())
    {
        fin >> word;
        if (word == "spam") N[0]++;
        else if (word == "ham") N[1]++;
        else
        {
            V++;
            fin >> wordnum;
        }
        int p = fin.tellg();
        fin >> c; //To check for newline. If its there, we skip the first eight characters of the new paragraph because those characters aren't supposed to be read
        if (c == '\n')
        {
            for (int i = 0; i < 8; i++) fin >> skip;
        }
        else fin.seekg(p);
    }

    cout << "\nSpam: " << N[0];
    cout << "\nHam :" << N[1];
    cout << "\nVocab: " << V;

    fin.close();

    return 0;
}

1 个答案:

答案 0 :(得分:1)

std::ifstream::operator>>()未读取变量中的\n;它掉了下来。如果您需要使用空格和\n符号进行操作,则可以使用std::ifstream::get()

相关问题