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 ; [B]cout << ' ' << myfile.txt << endl ;[/B] } 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.
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: #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 !
When you use the CPP Code Highlight it links to some of the commonly used functions to the official documentation or Help