how to read and write in files in c++?
Use fstream class... For text files, fstream f("example.txt",ios::in|ios::out); This file now you can both write and read if you want to only read then use only ios::in and remove the ios::out. just use the normal input like, int g; f>>g; for input and f<<"This is writing\n";for output.
that is to say use f>> and f<< instead of cin and cout? in PASCAL we just assign(input,'input.txt');reset(input); assign(output,'output.txt');rewrite(output); and we have to close(input);close(output); at the end of a program. so do i need to close files in c++?
yeah you need to close . just use f.close(); f<< and f>> are just simple input, output If you want better methods of input there is a getline function eg. char ch[30]; f.getline(ch,30,'\n'); This basically reads a max of 30 chars and ends if it reaches a '\n'character. There is a put function for output but that is basically of no use so f<< is pretty good.
Join our real-time social learning platform and learn together with your friends!