-
December 4th, 2018, 02:47 PM
#1
Really need help with my Array HW
So I need to write a c++ program where:
1)Read a sequence of integers from a file into an array
2) Pass that array of integers to a function which will compute and return the average (as a double).
3) Display the average returned from the function
I feel like I am overthinking it but here is what I have so far:
Code:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
int n = 0; //n is the number of the integers in the file ==> 12
int num;
int arr[100];
ifstream File;
File.open("numbers.txt");
while(!File.eof())
{
File >> arr[n];
n++;
}
File.close();
for(int i=0;i<12;n++)
{
cout << arr[i] << " ";
}
cout << "done\n";
return 0;
}
Last edited by VictorN; December 4th, 2018 at 03:27 PM.
Reason: add CODE tags
-
December 4th, 2018, 03:32 PM
#2
Re: Really need help with my Array HW
Well, did you test your code works as expected?
If it does then what is your next problem in writing the function "which will compute and return the average"?
if it does not work as expected then what is the problem?
And BTW, please always use the CODE tags while posting the code snippets!
Victor Nijegorodov
-
December 5th, 2018, 07:05 AM
#3
Re: Really need help with my Array HW
The 'usual' way to read numbers from a file into a fixed size array would be:
Code:
const size_t arrsize = 100; // Size of array
int arr[arrsize] = {0};
size_t n = 0;
for (; (n < arrsize) && (File >> arr[n]); ++n);
So that you don't overflow the array if more than the expected number of values from the file are tried to be read. Usually, though, in a situation like this then a container such as a vector would be used so that you don't need to care about the actual number of values read from the file.
Also, you have a code error in your loop to display the values of the array.
Now you just need to code the function to compute and return the average of an array!
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|