0

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?

2
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by Ancient Dragon
0

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)
{
}

Edited by Ancient Dragon: n/a

0

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......

Edited by WaltP: Added CODE Tags

0

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.

Edited by WaltP: Added CODE Tags again

0

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
    }
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.