Help with file input & output

Kappo's Avatar, Join Date: May 2009
Newbie Member
Hi, im having some trouble getting my head around the concept of file input/output.

I have written a basic program,and from my understanding(probably completely off),it should open a text file that i have named and saved in the same folder that my program is saved in.

The program will then write the variables i have created to the file and will display them.

Here is my code:

Code:
main()
{
      char c = 'J' ;
      int i = 5 ;
      string s = "Hello" ;
      
      ofstream myfile_out ; // create a file object for output
      
      myfile_out.open("myfile.txt") ; // this will open myfile.txt
      
      
      //now to write the data to the file
      myfile_out << s << ' ' << c << ' ' << i << endl ;
      myfile_out.close() ; // close the output file
      
      cout << "Your file contains :" << endl ;
      cout << ' ' << myfile.txt << endl ;
      
      }
However,my program does not work.I would like to keep it as simple as possible.Can anyone help point me in the right direction and explain were i am making mistakes.
I also understand that the last line is not correct,but what i am basically trying to do is output the contents of the file.Can someone please explain this to me.
0
SaswatPadhi's Avatar, Join Date: May 2009
~ Б0ЯИ Τ0 С0δЭ ~
Your mistakes :
(1) main () should have a return statement.
(2) The line which you mentioned in bold is completely incorrect, that's not the way to read files !
When you write to file, you open it in output mode, so to read files open it in input mode.


The correct code :

Code: c++
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
      char c = 'J';
      int i = 5;
      string s = "Hello";

      ofstream myfile_out; // create a file object for output
      myfile_out.open("myfile.txt"); // this will open myfile.txt

      //now to write the data to the file
      myfile_out << s << ' ' << c << ' ' << i << endl;
      myfile_out.close(); // close the output file

      cout << "Your file contains :" << endl;
      ifstream myfile_in;
      myfile_in.open("myfile.txt");
      char TChar;
      while( ! myfile_in.eof() )
      {
            myfile_in.get(TChar);
            putchar(TChar);
      }
      myfile_in.close();
      return 0;
}

PS : Can someone tell me why does the 'cout' get hyper-linked automatically ?? It's giving me a real headache !

Last edited by SaswatPadhi; 9May2009 at 07:54.. Reason: Mysterious hyperlink on 'cout' !
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by SaswatPadhi View Post
PS : Can someone tell me why does the 'cout' get hyper-linked automatically ?? It's giving me a real headache !
When you use the CPP Code Highlight it links to some of the commonly used functions to the official documentation or Help