eof()如何读取文件中的行?

问题描述 投票:0回答:1
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ofstream files;
    files.open("FIRST.TXT");
    string abc;
    getline(cin, abc);
    files << abc;
    files.close();
    ifstream fin;
    fin.open("FIRST.TXT");
    ofstream fout;
    fout.open("SECOND.TXT");
    char word[30];
    while (!fin.eof())
    {
        fin >> word;
        if (word[0] == 'a' || word[0] == 'e' || word[0] == 'i' || word[0] == 'o' || word[0] == 'u')
            fout << word << " ";
        cout << word << endl;
    }
    fin.close();
    fout.close();   
}

此代码将元音字母开头的单词存储在另一个文件中,而不是我们从中读取数据的文件中。

char word[30]如何准确输入单词,eof()是否可以逐个空格地工作?

为什么循环检查单词而不是字符,还是空格后的第一个字符,为什么?

c++ file-handling eof
1个回答
0
投票

while循环中的eof检查不起作用。您会在SO中找到大量页面来解释这一点。 Nate Eldredge在上面的评论中给出了一个示例:Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?

此外,我建议使用更现代的C ++语言元素。这样,您就可以避免所有细腻的东西。

请参见以下示例:

#include <iostream>
#include <sstream> 
#include <string>
#include <algorithm>
#include <iterator>

std::istringstream testFile(R"(Lorem ipsum dolor sit amet, 
consetetur sadipscing elitr, sed diam nonumy eirmod tempor 
invidunt ut labore et dolore magna aliquyam erat, sed diam 
voluptua. At vero eos et accusam et justo duo dolores et ea 
rebum. Stet clita kasd gubergren, no sea takimata sanctus est 
)");

int main() {

    std::copy_if(std::istream_iterator<std::string>(testFile),{},
        std::ostream_iterator<std::string>(std::cout, "\n"),
        [](const std::string& s) { return (0x208222 >> (s[0] & 0x1f)) & 1; });

    return 0;
}

您可以看到,整个任务可以用一个copy_if()语句完成。

而且,数据来自何处也没有关系。目前,我正在使用std::istringstream。但是,您也可以打开一个文件,然后将std::ifstream变量放入std::istream_iterator。与输出相同。目前,我正在写std::cout。您也可以在此处放置一个开放的std::ofstream变量。

所以,现在到std::copy_if()。请see here进行描述。 copy_if()接受2个输入迭代器作为源的开始和结束,一个输出迭代器和一个条件。

istream_iterator基本上将调用提取器istream_iterator,并从流中提取operator>>。它将被调用,直到命中文件的末尾(或发生错误)。结束迭代器由空括号默认初始化程序给定。如果您选择std::string,则将看到默认构造函数等于最终迭代器。

为了写入数据,我们将使用look here,它将所有复制的字符串写入输出流。

对于std::ostream_iterator中的条件,我们使用lambda,它检查字符串的第一个字符是否是元音。

我已详细描述了检测元音的算法std::ostream_iterator

所以,非常简单。仅需一个声明。

© www.soinside.com 2019 - 2024. All rights reserved.