Help

Hello I'm trying to write a simple code to read ten numbers from my "data.txt" file and it's only reading the first number. How do I get it ro read the whole file is it the (!fin.eof)?? here are the numbers
12
14
19
98
78
65
54
34
76
45

my out put file is printing this:
largest number is:12
smallest number is:12


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
 #include <iostream>
#include <fstream>

using namespace std;

int main()
{
	ifstream fin;
	ofstream fout;	
	fin.open("data.txt");
	fout.open("output.txt");
	int a;
	int count=0;
	int max = INT_MIN;
	int min = INT_MAX;

	for (int i = 0; i <= count; i++)
	{
		fin >> a;

		if (a > max)
		{
			max = a;
		}
		if (a < min)
		{
			min = a;
		}
	}
	fout << "largest number is:" << max << endl;
	fout << "smallest number is:" << min << endl;
	
	system("pause");
	}
first include string and

1
2
3
4
5
6
7
8
9
string line;
if (fin.is_open())
  {
    while ( getline (fin,line) )
    {
      cout << line << '\n';
    }
    fin.close();
  }

you can read all numbers if you use this
Last edited on
One qualifier for the for statement to continue is i <= count. i starts as 0 and count = 0, so after the first time i is increased by 1 and no longer is <= 0. count needs to equal 9 for that to work.

Also, you could put all the ints in one line with:
int a, count = 0, max = INT_MIN, min = INT_MAX;
Last edited on
Thanks for the reply where in my code would I place that?
Reitrahc,

You sir are a gentleman and a patriot:) Thanks that was the ticket
1
2
3
4
5
6
7
8
9
10
11
12
while ( fin >> a )
    {
      if(a>max)
      {
        max=a;
      }
      if(a<min)
      {
        min=a;
      }

    }
Last edited on
You're welcome, although this code only works to check a file for 10 numbers. What pcplusplus used works in more cases, I simply wanted you to know how to fix your own code. I know the feeling of being given the right answer, but not understanding how to use it.
Last edited on
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
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	ifstream fin;
	ofstream fout;
	fin.open("data.txt");
	fout.open("output.txt");
	int a;
	int max = INT_MIN;
	int min = INT_MAX;

	while(fin >> a)
{
		if (a > max)
		{
			max = a;
		}
		if (a < min)
		{
			min = a;
		}
	}
	fout << "largest number is:" << max << endl;
	fout << "smallest number is:" << min << endl;

	system("pause");
	}

use this
Last edited on
Topic archived. No new replies allowed.