View Single Post
Old Dec 4th, 2007, 7:04 PM   #24
lectricpharaoh
Caffeinated Neural Net
 
lectricpharaoh's Avatar
 
Join Date: Jun 2005
Location: Dry west coast of Canada
Posts: 1,031
Rep Power: 5 lectricpharaoh will become famous soon enough
Re: read integers from file into an array

Listen to Sane regarding using the index. You don't need to track the maximum value. You only need to track its position within the array, and this allows you to get the value from the array, since you know where it's stored.

Anyways, while other people were replying to you, I whipped up this. It's exactly what you need, but don't just use this for your homework. I'm doing it so you can see how it's done, and I'm only posting code because you've shown you're trying, but if you hand in my work rather than understanding it enough to do it yourself, it'll only hurt you in the long run.
c++ Syntax (Toggle Plain Text)
  1. #include <fstream>
  2. #include <iostream>
  3. #include <string>
  4.  
  5. int main(void)
  6. {
  7. std::ifstream inFile;
  8. std::ofstream outFile;
  9. int myArray[100],
  10. maximumValuePosition = 0,
  11. minimumValuePosition = 0,
  12. count = 0;
  13.  
  14. inFile.open("inputNums.txt");
  15. if(!inFile) // test if stream is valid, ie is file open?
  16. {
  17. std::cerr << "Unable to open input file, aborting..."
  18. << std::endl;
  19. return 1;
  20. }
  21.  
  22. outFile.open("finalResults.txt");
  23. if(!outFile)
  24. {
  25. std::cerr << "Unable to open output file, aborting..."
  26. << std::endl;
  27. inFile.close();
  28. return 2;
  29. }
  30.  
  31. while((count < 100) && (inFile >> myArray[count]))
  32. ++count;
  33.  
  34. for(int x=0; x<count; ++x)
  35. {
  36. if(myArray[x] > myArray[maximumValuePosition])
  37. maximumValuePosition = x;
  38. if(myArray[x] < myArray[minimumValuePosition])
  39. minimumValuePosition = x;
  40. }
  41.  
  42. if(count == 0)
  43. {
  44. outFile << "There were no values in the input file." << std::endl;
  45. }
  46. else
  47. {
  48. outFile << "The maximum value is "
  49. << myArray[maximumValuePosition]
  50. << ", found at array index " << maximumValuePosition
  51. << ".\n";
  52. outFile << "The minimum value is "
  53. << myArray[minimumValuePosition]
  54. << ", found at array index " << minimumValuePosition
  55. << ".\n";
  56. outFile << "There are " << count << " values." << std::endl;
  57. }
  58.  
  59. inFile.close();
  60. outFile.close();
  61. return 0;
  62. }
__________________
And once again, Probability proves itself willing to sneak into a back alley and service Drama as would a copper-piece harlot.
- Vaarsuvius, Order of the Stick
lectricpharaoh is offline   Reply With Quote