file reading

i have a file that has 1000 numbers in a list form, how would i tell the program to put 10 numbers in a row \n 10 numbers in a row \n 10 numbers in a row.... and keep going until the input file runs out of numbers?
Use some nested loops; one to print out a line of 10 numbers, and another print to out 1000/10 lines.
this is what i have but i don't think it reads the numbers or the loop doesn't work
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<fstream>
#include<cstdlib>
#include<iostream>
using namespace std;

int main()
{
	ifstream fin;
	ofstream fout;

	int num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;

	fin.open("numbers.txt");
	if (fin.fail())
	{
		cout<< "Input file opening failed.\n";
		exit(1);
	}

	fout.open("output.dat");
	if(fout.fail())
	{
		cout << "Output file opening failed.\n";
		exit(1);
	}

fin>>num1>>num2>>num3>>num4>>num5>>num6>>num7>>num8>>num9>>num10;
fout<<num1<<" "<<num2<<" "<<num3<<" "<<num4<<" "<<num5<<" "<<num6<<" "<<num7<<" "<<num8<<" "<<num9<<" "<<num10<<endl;
while (!fin.eof())
{
fin>>num10;
cout<<num10<<endl;
}

fin.close();
fout.close();
return 0;
}
You could put line 27-28 inside the loop instead of what you have there now.

Having eof() in the loop condition tend to make one iteration too many. http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5

I think you could do this with just one int variable instead of ten. You could use a nested loop like Zhuge said or keep track of a counter and check with an if statement if it's time to add a newline character.
i got it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<fstream>
#include<cstdlib>
#include<iostream>
using namespace std;

int main()
{
	ifstream fin;
	ofstream fout;

	double num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;

	fin.open("numbers.txt");
	if (fin.fail())
	{
		cout<< "Input file opening failed.\n";
		exit(1);
	}

	fout.open("output.txt");
	if(fout.fail())
	{
		cout << "Output file opening failed.\n";
		exit(1);
	}
	fin>>num1>>num2>>num3>>num4>>num5>>num6>>num7>>num8>>num9>>num10;
	fout<<num1<<"  "<<num2<<"  "<<num3<<"  "<<num4<<"  "<<num5<<"  "<<num6<<"  "<<num7<<"  "<<num8<<"  "<<num9<<"  "<<num10<<"  "<<endl;
while (!fin.eof())
{
	fin>>num10;
	fout<<num10<<"  ";
	fin>>num1>>num2>>num3>>num4>>num5>>num6>>num7>>num8>>num9>>num10;
	fout<<num1<<"  "<<num2<<"  "<<num3<<"  "<<num4<<"  "<<num5<<"  "<<num6<<"  "<<num7<<"  "<<num8<<"  "<<num9<<"  "<<endl;
}

fin.close();
fout.close();
return 0;
}
Topic archived. No new replies allowed.