Sunday, July 12, 2009

C++ question--how to write a program that searches a file of numbers and outputs the largest & smallest ones:?

This is what I have thus far...and now I am stuck. I don't understand the I/O streams very well...and I'm not sure what to do at this point. Any guidance is greatly appreciated :)





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


using namespace std;





int main() {


int largest = 0;


int smallest = 0;


int testValue = 0;


ifstream inStream;





inStream.open("integers.txt");


if (inStream.fail())


{


cout %26lt;%26lt; "Input file opening failed.\n";


exit(1);


}





char next;


inStream.get(next);


while (! inStream.eof())


{


cout %26lt;%26lt; next;


inStream.get(next);


}





inStream.close();





cout %26lt;%26lt; "The largest integer is: " %26lt;%26lt; largest %26lt;%26lt; endl;


cout %26lt;%26lt; "The smallest integer is: " %26lt;%26lt; smallest %26lt;%26lt; endl;





return 0;


}


// function main

C++ question--how to write a program that searches a file of numbers and outputs the largest %26amp; smallest ones:?
Ahh, it's been a long time since I programmed in C++... Let's see... You're almost there, provided the syntax is correct...





A few things... Why is next a char? I thought you wanted to be reading numbers from the file, not characters?





Second - read the first number before the loop and assign it to both largest and smallest. Because it will be both largest and smallest, if it's the first one... Then use two if's inside the loop to compare the number you just read to largest, and see if it's larger then assign its value to it... Respectively with the smallest....





And that should be about it....





I would've modified your code and posted it... but it's your homework, right? So it's better if you do it....





LEM.
Reply:You will want to use the %26gt;%26gt; operator in a loop, as in:





inStream %26gt;%26gt; testValue; // reads testValue from inStream


// do tests to set smallest and largest





It works the same way that you would use it with cin. Note that this will fail if the file is not formatted correctly for the type (in this case, int).

secret garden

No comments:

Post a Comment