Hi folks.

I have a text file with a thousands of rows of numbers in it.
For example:

1 2 4 6 11 13 19 21 66 97 101 ........
1 3 9 12 18 26 44 56 98 113......
...........
......

What I want to do is find the maximum number that's in the file.
My thoughts are:

1 - the numbers are all strings, not integers, so I can't easily get the max val.
2 - do I need to use an array to store all the numbers in and calculate the max val from there?
3 - do I need to use itoa to convert the strings into integers?
4 - I need some way of making the program recognise a whole number (i.e. read in the data until you get to a space and then it will know its got a whole number).

Can anyone help me? Is there some fairly straight forward code I can use to do this?

read the file as integers not strings. Then just keep track of the maximum integer read. If you use ifstream then the >> operator will convert the number to an integer, your program won't have to do the conversion.

int number;
ifstream in("filename.txt");
while( in >> number)
{
}

I'm trying to use this code now:

while(datFile >> Val) 
{ 
if (Val > n) 
{ 
n = Val; 
} 
while(getline(datFile, line)) 
{ 
m++; 
} 
}

But it won't calculate both n and m. If I comment out the getline loop for calculating m, then n works (calculates the max value in the file).

Help......

I've got it working.

while(datFile >> Val)
	{	
		if (Val > n)
		{
			n = Val;
		}
	}

	datFile.clear();
	datFile.seekg(0);
		
	while(getline(datFile, line))
	{
		m++;
	}

Thanks for your help.

Sorry I didn't respond earlier -- I was at work.

You didn't say you needed to count the number of lines in the file. To do that use getline(), then split up the line into integers using stringstream

#include <sstring>
...
std::string line;
while( getline(dataFile, line) )
{
    m++;
    stringstream str(line);
    while( str >> Val )
    {
       // blabla
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.