i tried this

#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;


int main() 
{
    // Declare input stream
    ifstream fin;
    int min, max, val;
    int isFirst = true;
    fin.open("inFile.txt");



    fin >> isFirst;
    min = isFirst;
    max = isFirst;

    while (fin >> val)
    {

          fin >> val;
          if (val < min)
          val = min;
          else
          val = max;

    }



    fin.close();

    cout << "Largest value is " << max << ", smallest value is " << min << "\n";
    return 0;
}

and it prints this
Largest value is 1, smallest value is 1
Press any key to continue
can someone suggest me what's i am doing wrong here

Dani AI

Generated

A few concrete observations pulled from the thread and a short checklist of fixes so the reported symptoms are easy to avoid in future.

Root causes seen here

  • The program was initializing and updating the wrong variables (the min/max update was reversed), and at least one loop iteration extracted the next number twice, effectively skipping values. The average routine only updated sum/count after the loop and used an increment-expression incorrectly, which produced the last value as the average. File-open or working-directory mismatches are another common source of "it works for me" vs. "doesn't work for you" behavior.

Practical checklist (apply in this order)

  • Verify the input file actually opened before reading; handle the open failure explicitly.
  • Read the first numeric token and use it to initialize min, max, running sum and count so the loop deals only with subsequent tokens.
  • In the main loop extract exactly one token per iteration; for each token compare and update min and max (assign the current token into min or max when appropriate), add the token to sum, and increment the count with a plain increment (avoid combining assignment with a postfix increment).
  • After the loop compute the average only if count > 0 and use floating-point division so fractional averages are preserved.

Debugging tips and final notes

  • Print each value as it is read to detect double-extraction or malformed tokens. Check for stray non-numeric characters in the file and for the executable’s working directory. Compiler warnings and a quick debugger run usually reveal the extra extraction or wrong-assignment bug immediately. Credits to and for the read-first initialization approach, and to and for pointing out the sum/count placement and increment issues; ’s follow-up confirms the root cause was an implementation mistake rather than the algorithm itself.

Recommended Answers

All 14 Replies

while (fin >> val)
    {

          fin >> val;
          if (val < min)
          val = min;
          else
          val = max;
		  
    }

Change min and/or max, not val.

while ( fin >> val )
   {
      if ( val < min )
      {
         min = val;
      }
      if ( val > max )
      {
         max = val;
      }
   }

It might also be helpful to post the contents of "inFile.txt".

i tried the way u suggested me but it still gives same output
the content of "inFile.txt" is
100
45
74
45
86
94
75
96
56
85
82
88
88
56
77

>i tried the way u suggested me but it still gives same output
Odd.

#include <fstream>
#include <iostream>
using namespace std;


int main() 
{
   ifstream fin("inFile.txt");
   int min, max, val;
   if ( fin >> val )
   {
      min = max = val;
      while ( fin >> val )
      {
         if ( val < min )
         {
            min = val;
         }
         if ( val > max )
         {
            max = val;
         }
      }
   }
   cout << "Largest value is " << max << ", smallest value is " << min << "\n";
   return 0;
}

/* my output
Largest value is 100, smallest value is 45
*/

i tried every possible way u suggested me and it still doesnt work. could it be some other problem?

Did you copy and paste what dave wrote and compiled it?

>fin >> isFirst;
I think you mean:

fin>> val;

isFirst doesn't strike me as a data variable, it seems more like a status variable. You don't even need it. Oddly enough, I didn't bother looking at Dave's code, but my solution is only slightly different (but it avoids undefined behavior in the case of an empty or non-existent file):

#include <fstream>
#include <iostream>
using namespace std;

int main() 
{
  ifstream fin("inFile.txt");
  int val;

  if (fin >> val) {
    int min, max;

    min = max = val;

    while (fin >> val)
    {
      if (val < min)
        min = val;

      if (val > max)
        max = val;
    }

    cout << "Largest value is " << max << ", smallest value is " << min << "\n";
  }

  return 0;
}

Great minds think alike, I suppose.

>i tried every possible way u suggested me and it still doesnt work.
Then instead of looking at the suggestions and implementing them they way you think they should be done, actually try them as they are written. In my experience, Dave doesn't post untested code.

thx a bunch guys
i am sorry dave it was my fault in implementing codes . its working
thx

again need help guys
trying to calculate average of all numbers in previous program
here is what i did but it gives average = 77

#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;



int main() 

{
   	
   ifstream fin("inFile.txt");
   ofstream fout("outFile.txt");
   
   if (fin.fail())
   {
	   cout<<"Input file opening failed.\n";
	   exit(1);
   }
   if (fout.fail())
   {
	   cout<<"output file opening failed.\n";
	   exit(1);
   }
   int min, max, val;
   double sum = 0;
   int count = 0, next ;
          
 
	  
   if ( fin >> val )
	   
   {
	     
	  
      min = max = val;
      while ( fin >> val )
      {
		 
			  
         if ( val < min )
         {
            min = val;
         }
		 
         if ( val > max )
         {
            max = val;
		 }
		  
      }
	  sum = sum+val;
	   count=count++;

   }
           
   

 sum=sum/count;
	

   
   fout<<"average score is:"<< sum << "\n";
   cout<<"average score is:"<< sum << "\n";

   
   fout << "Largest value is " << max << ", smallest value is " << min << "\n";
   cout << "Largest value is " << max << ", smallest value is " << min << "\n";
   fin.close();
   fout.close();
   
   return 0;
}

Code tags added. -Narue

what am i doing wrong here?

>here is what i did but it gives average = 77
Um...what's the problem with getting the correct answer?

The average is 76.4666.

desidude, since your sum and count are modified after the while loop, only the last value of your numbers gets added to sum, and count gets incremented once, from zero to one. And 77 is your last value.

Just put the

sum = sum+val;
   count=count++;

inside your while loop, and it shuld work.

Zyruz, i tried that before but it gives 74.78 which is 1047( 100 less than total(1147))/14(it is suppose to be 15).

Don't forget to account for the first value:

if ( fin >> val )
  {
    sum += val;
    ++count;
    min = max = val;

    while ( fin >> val )
    {
      if ( val < min )
      {
        min = val;
      }

      if ( val > max )
      {
        max = val;
      }

      sum += val;
      ++count;
    }
  }

On a side note, this is very, very wrong:

count=count++;

It modifies count twice between sequence points, which is undefined.

thx alot guys

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.