me1234
me1234

Reputation: 57

Why is my C++ code with file output not working?

I didn't got any errors, but my C++ code is still not working. It's really simple:

#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    string a;

    ofstream fout("char.out");
    ifstream fin("char.in");

    fin >> a;
    fout << a;

    return 0;
}

char.in after running:

uiui

char.out after running:


Did I missed anything simple in my code?

P. S. : I got Norton Antivirus and my project folder is missed from AutoCheck.

Upvotes: -3

Views: 675

Answers (1)

Mahdy.n
Mahdy.n

Reputation: 73

in fact for reading and writing you should open and close file but you didn't close.

Also you have two files where you have done writing from one file and reading from another file, I wonder how you expect to get the correct output.

this is how it should be :

#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    string a;

    ofstream fout("char.out");
    
   //  check if file is created
   if(fout.is_open()){
   //  do writing in file
  
   }
    else 
     cout << "can not open file\n";

    fout.close();

//-----------reading the file----------



    // use the same file
    ifstream fin("char.out");

    if(fun.is_open()){
     // do reading from file
     std::cout << a << std::endl;
    }
     else
      cout << "can not open file\n";
     
     fin.close();
    return 0;
}

And if you want to add a line of text to the end of the file, you must add:

ofstream fout("filename" , ios::app);

Upvotes: -4

Related Questions