lundi 18 octobre 2021

Why is Appended content not showing up on reading from a file in C++?

Hi, guys please look at this code first then i will ask my question -

#include <bits/stdc++.h>
#include <fstream>

using std::cout; 
using std::cin; 
using std::endl;

int main() {

    
        std::ofstream out_file ("outfile.txt");  /* creates a outfile.txt */
       

        if(!out_file) { // checks files existence

            std::cerr<<"Error bruh!"<<endl;
            return (1);
        }


        int num = 100;
        double total = 456.78;
        std::string name = "atik";

        out_file<<num<<"\n"     // writing to the file
                <<total<<"\n"
                <<name<<endl;

     

/* Reading from file, because i want to! - */

        std::ifstream in_file("outfile.txt"); // will open outfile for reading.

            char c;

            while(in_file.get(c)) {

                cout<<c;
            } 

Output (as expected) - 100
456.78
atik

Right Now My output.txt file is - (as expected)
100
456.78
atik

/* Appending the file that we just created - */

        std::ofstream out_file2 ("outfile.txt", std::ios::app);   
  

            cout<<"\nEnter something to write in file : "<<endl;

            std::string line;

           getline(cin,line);

           out_file2<<line;  // writes to out_file2

/* Reading from file again - */

        std::ifstream in_file2("outfile.txt"); // will open outfile.txt for reading.

       if( !in_file2 ) {

        std::cerr<<"File didn't open. Error encountered."<<endl;
    }

            char ch;

            cout<<endl;

            

            while( in_file2.get(ch) ) {

                cout<<ch;
            }

Output (unexpected? why?)- 100
456.78
atik

        in_file.close();
        in_file.close();
        out_file.close();
        out_file2.close();
         return 0; }

Now My outfile..txt is - (as expected)

100
456.78
atik
Hello there

Then why tf my output for in_file2 isn't showing Hello there? Why it truncates the Hello there, Can someone please explain??

Aucun commentaire:

Enregistrer un commentaire