Jordan P
Jordan P

Reputation: 31

How to put the newline while taking data from file?

I need to take data from file and then want to save it in a string , after saving it in string i wants to put the data in the same file from where i get that data.PROBLEM is while taking data,it is notdetecting my new line . Let see the example.

I have a file "check.txt" in which the data is like this: ABC new line DEF new line XYZ new line

Now i wants to send the same data in file again but instead of sending the same data it is sending it like this: ABC DEF XYZ.

How can i add back in the format number 1?

Here is the code i tried:

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

void abc()
{
    ifstream fin("check.txt");
    string line,line1;
    while (fin)
    {
        getline(fin,line);
        line1.append(line.begin(),line.end());

}
fin.close();

    ofstream fout;
    fout.open("check.txt");
    while (fout)
    {
    {

        fout<<line1<<endl;
    //  fout<<"done"<<endl;
        cout<<"done"<<endl;
    }
    break;
}
fout.close();
}
int main()
{
    abc();
}

Upvotes: 2

Views: 78

Answers (2)

Jorge Omar Medra
Jorge Omar Medra

Reputation: 988

Bilai.

Try this:

While your program is getting each line write it to the stringstream, using the same loop:

void abc()
{
    ifstream fin("check.txt");

    string line;
    stringstream out;
    while (fin)
    {
        getline(fin, line);
        out << line << '\n'; //use character '\n' instead of endl, to avoid flushing the stream every loop.
    }
    fin.close();

    ofstream fout;
    fout.open("check.txt");
    fout << out.str();
    fout.close();
}

Upvotes: 2

xslr
xslr

Reputation: 351

When getline reads a line, it discards the newline character. You will need to reinsert newline characters when appending line to line1.

Upvotes: 2

Related Questions