Printing a minimum value from an array in a text file

Hi there,

I am trying to have my program print an array and also print the minimum value, all from a text file called numbers.txt
I have successfully printed the array with no errors, but I'm struggling to format the printing of the minimum value. I need to do this all from the file using getMin.

Any help would be greatly appreciated. Here's what I have so far:
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

const int ARRAY_SIZE = 100;

void readNumbers(string filename, string numbers[], int& count)
{
	ifstream infile;
	infile.open(filename.c_str());
	
	if(!infile.is_open())
	{
		cout << "could not open file" << endl;
		return;
	}
	
	char c = infile.peek();
	
	while(!infile.eof() && count < ARRAY_SIZE && c!= '\n')
	{
		getline(infile, numbers[count]);
		
		count++;
		
		c= infile.peek();
	}
	infile.close();
	
}

void printNumbers(string numbers[], int count)
{
	cout << "... Printing Array ..." <<endl;
	for(int i=0; i <count;i++)
	{
		cout << numbers [i] <<endl;
	}
}

int getMin(string numbers[0], int count) // problems start here
{

	int min;
	
	for(int i=0; i<count; i++)
	{
		if(numbers[i] < min)
		min= numbers{i}
	}
	return min;
}

cout << "The minmimum value is: " << min <<endl;	
} //everything else sans this block runs smoothly

int main()
{
	string numbers[ARRAY_SIZE];
	int count = 0;
	
	string inFileName= "numbers.txt";
	readNumbers (inFileName, numbers, count);
	printNumbers(numbers, count);
	
	return 0;
	
}


Thank you so much in advance
You're reading the numbers into an array of strings. Why not read them into an array of ints?

readNumbers is much more complicated than necessary. If you convert the array to ints, then you can read them with
1
2
3
        while (count < ARRAY_SIZE  && (infile >> numbers[count])) {
            count++;
        }



Line 50: Min is uninitialized the first time through the loop. A handy way to deal with this is to initialize min to the first element in the array, and then have the array from from 1 to count instead of 0 to count:
1
2
3
4
5
6
7
        int min = numbers[0];

        for(int i=1; i<count; i++)
        {
                if(numbers[i] < min)
                    min= numbers[i];
        }

This still has a bug when count is zero. I'll let you decide whether to fix it.

Line 54 ends the function getMin(), but you have more code at lines 56 & 57. ALso, should getMin() simply return the minimum value or should it print it? Decide what it should do, write a comment to reflect the design, and then make the code do what you want.

Don't forget to call getMin() in main().


Thank you so much, this helps a ton!
Topic archived. No new replies allowed.