It reads numbers from a file and then it is supposed to tell the user the highest and lowest number. Seems like all the info I can find is having the user type in numbers not read them from a file and I can't seem to figure out how to make it work for my use.
I did get it to find the highest number but the lowest seems to always be 0 or if I make the lowest number start as a '1' then the lowest turns into 48.
Any ideas?
#include<iostream>
#include<fstream>
#include<cstdlib>
usingnamespace std;
/*
the vareables
*/
double highest, lowest, current, number;
char s;
int main() {
ifstream instream;
string s; // makes a string named s
cout << "Enter a file name: \n"; // takes in file name
cin >> s; // name of file
instream.open(s.data()); // tells it what file to open and read off of
if (instream.fail()) {
cout << "Failed to open file! \n";
exit(1);
}
while (instream >> current) {
number = current;
lowest = (number <= lowest)?number:lowest; // this doesn't seem to work
highest = (number >= highest)?number:highest; /* This seems to work for
the highest number but when I convert it for the lowest it doesn't */
}
cout << "The lowest number is " << lowest << endl;
cout << "The highest number is " << highest << endl;
instream.close();
return 0;
}
#include<iostream>
#include<fstream>
int main()
{
std::string file_name ;
std::cout << "Enter a file name: " ;
std::cin >> file_name ;
std::ifstream instream( file_name.c_str() ) ;
if( instream.fail() )
{
std::cout << "Failed to open file! \n";
return 1 ;
}
double current ;
if( instream >> current ) // read the first number in the file
{
double lowest = current ;
double highest = current ;
while( instream >> current )
{
if( current < lowest ) lowest = current ;
elseif( current > highest ) highest = current ;
}
std::cout << "The lowest number is " << lowest << '\n'
<< "The highest number is " << highest << '\n' ;
}
else // could not read the first number
{
std::cout << "Failed to read any number from file! \n";
return 1 ;
}
}