Reading and writing arrays from file

May 13, 2013 at 12:59pm
Can someone please help me with a short programme to read and then write a file.

Basically I wish to open a file say "numbers.text"

numbers.txt contains these four number in this order

2 4
3 1

I wish to read them into my app as a(0), a(1), a(2) and a(3)
So a(0)=2, a(1)=4, a(2)=3 and a(3)=1

Next I wish to open a file "order.txt" and write these numbers after sorting as

1 2
3 4.

It is fairly basic but I'm new to C++ and generally trying to teach myself everything from scratch.

Thanks in advance.
May 13, 2013 at 1:04pm
closed account (N85iE3v7)
Hey I'd consult

http://www.cplusplus.com/doc/tutorial/files/

In the last 2 years my coworkers used C library functions to read and write files, so I sort of lost fluency in the C++ way, which is better IMO.
May 13, 2013 at 1:08pm
Thank you

After reading that I get the idea but not quite enough.

I can work out how to order the numbers, that's the easy bit. It is just how to read and write number arrays to file.
May 13, 2013 at 1:28pm
Reading from a file is very much the same as getting input from the user via cin.
1
2
3
4
5
ifstream infile("numbers.txt");
int count = 0;
int a[50]; // allocate more space than is required.

while (infile >> a[count++]); // read all the data into array  

After the while loop ends, count will contain the number of values which were successfully read from the file.
May 13, 2013 at 1:32pm
Thanks I'll adapt that into what I have so far. :)
Topic archived. No new replies allowed.