How to get information from .txt

Hello everyone. I'm tryng to code but need some help, its about ifstream and ofstreams. I have some code.

1
2
3
4
5
6
7
8
9
ofstream numbers;
numbers.open("MyNumbers1.txt");
	
	
for(int i=0; i<10; i++){
numbers << rand()%10 << endl;
} 
	
numbers.close();


it warks but i want get some function and call this function in main. I have no idea how to do this so please give me some little example.
Last edited on
[link]
http://www.cplusplus.com/doc/tutorial/functions/
[/link]

Hopefully the above link tags will work. If not, you can copy paste the address to your address bar.

It sounds like you haven't used functions before, and the above tutorial gives a good explanation.

If you don't need your ofstream anywhere outside the function, you could write it with no parameters and a void return type and simply copy paste the nine lines above into the function definition.
Be aware that if you do it this way, every time you call your function it will overwrite the entire output file.

I guess I didn't need the link tags. Oh well.
Last edited on
ty. ill try this. thanks a lot
@skybay,

No there is no link tag. All you need is a space preceding the line or start it on its own line and a space or new line at the end and it will show up as a clickable link.

Hello RanGH,

If you need to pass the "ofstream" to a unction it will need to be passed by reference, i.e., void SomeFunction(ofstream& name) and it will work fine.

Or if the function is the only place you use the output stream just open the file there.

I get the impression that you will need to open the file stream in main and pass it to the function(s) that will need it. In that case I would suggest opening the file in this way:
std::ofstream(fileName, std::ios::trunc | std::ios::ate);. The "tunc" will clear the file before each use and "ate" works with "trunc" to append the file. Later you could remove std::ios::trunc | and change "ate" to "app" to append the file for each output to the file.

Hope that helps,

Andy
ty Andy.
Topic archived. No new replies allowed.