如何读取文件,反转部分文本并将相反的部分写在C ++上的另一个文件中?

时间:2018-05-03 01:25:08

标签: c++ string file

我需要帮助,我编写代码,做了相反的事情,但我不能把它写在另一个文件上。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream par2("C:/fajllat/f1.bin", ios::in);
    string line;

    for (int i = 1; !par2.eof() ; i++)
    {
        getline(par2, line);

        if (i < 5 || i >14)  continue;
        line = string(line.rbegin(), line.rend());

    }
    par2.close();

    ofstream mbrapsht ("C:/fajllat/f3.bin", ios::out);

    mbrapsht << line;

    mbrapsht.close();
    cin.get();cin.get();

    return 0;
}

当我检查文件时,f3.bin文件为空

2 个答案:

答案 0 :(得分:1)

你有正确的想法。你错过的是,如果你想写反转的行,你需要在循环中写入它们或者将它们存储在后面。你没有做这些事情。

目前发生的事情是你在每个循环中覆盖line。而那个字符串中剩下的就是你之后写的东西。事实证明,对于你的情况,这是一个空字符串。

让我们对您所拥有的内容进行微小的更改:

// (*) Open the output file before looping
ofstream mbrapsht("C:/fajllat/f3.bin", ios::out);

for (int i = 1; !par2.eof() ; i++)
{
   getline(par2, line);
   if (i < 5 || i > 14)  continue;
   line = string(line.rbegin(), line.rend());

   // (*) output the line - you also probably want an end-of-line
   mbrapsht << line << std::endl;
}

现在,没关系。但它确实有一个问题,如果getline失败,你的代码仍然会再次运行循环体。如果getline遇到文件末尾(或其他一些错误状态),则会发生这种情况,您的循环在下一次迭代之前不会被捕获(或者如果错误不是EOF,则可能永远不会)。

所以,一个更好的选择可能是:

for(int lineNo = 1; std::getline(par2, line); ++lineNo)
{
    if (lineNo >= 5 && lineNo <= 14)
    {
        std::reverse(line.begin(), line.end());  // (*) requires <algorithm>
        mbrapsht << line << std::endl;
    }
}

请注意,我也将您的测试条件反转并删除了continue。一般情况下,我会在循环中避免使用continuebreak,除非不使用它们会导致代码难以理解或一目了然。它是一种风格/可维护性的东西。拿走或离开它。

答案 1 :(得分:0)

请参阅此代码段。对于逐行撤消,您可以在推入getline()之前使用vector<string>代替并反向。

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

using namespace std;
int main()
{
    string str;
    ifstream par2("D:\\MyFolder\\try.txt", ios::in);

    if (par2.is_open())
    {
        stringstream strStream;
        strStream << par2.rdbuf();
        str = strStream.str();
        cout << str << endl;
        par2.close();
    }

    cout << "\n\nReversing ...\n\n";
    std::reverse(str.begin(), str.end());
    cout << str << endl;


    ofstream mbrapsht("D:\\MyFolder\\try2.txt", ios::out);
    mbrapsht << str;
    mbrapsht.close();

    return 0;
}

输出:

enter image description here