How do I make a loop that will take numbers from an external file and then list the numbers on the screen, then calculate the sum of those numbers and show it?
I'm desperate
Thanks
How do I make a loop that will take numbers from an external file and then list the numbers on the screen, then calculate the sum of those numbers and show it?
I'm desperate
Thanks
Have you got any code to start with?
Have you read the FAQ? If this is home work nobody will write your program for you.
Make a start, post your code, and we'll help you get it right.
Code:#include <fstream> #include <iostream> using namespace std; const size_t MAX = 10; int main() { { int i = 0, numbers[MAX], number = 0, sum_of_num = 0; //LOAD THE DATA INTO AN ARRAY for(i = 0;i < MAX;i++) { cout<<"Enter a number:";cin>>number; numbers[i] = number; } //CREATE AN OUTPUT FILE AND WRITE THE DATA TO IT fstream file; file.open("MyNumbers.txt",ios::out|ios::binary); file.write((char *)numbers,MAX * sizeof(int)); file.close(); //RE-OPEN THE FILE AS INPUT AND READ FROM IT file.open("MyNumbers.txt",ios::in|ios::binary); file.read((char *)numbers, MAX*sizeof(int)); //PRINT AND SUM WHILE TRAVERSING THE ARRAY for(i = 0;i < MAX;i++) { cout<<numbers[i]<<endl; sum_of_num +=numbers[i]; } //DISPLAY THE TRUTH AND THE SUM cout<<"This is your early christmas present" <<endl <<"The sum is " <<sum_of_num; } return 0; }
Last edited by DISGUISED; 05-08-2002 at 08:23 PM.
Of course, I've been wrong before. There's always somebody willing to show they can open a file and add a couple of variables. I now stand humbled and corrected, and suggest that we re-write the FAQ to read.... "....Don't bother attempting anything for yourself, just post your issue and someone will come forth with the code"
That having been said, the code looked quite tidy I must say.
The guy was close. I guess you didn't see this thread did ya?Originally posted by Azuth
Of course, I've been wrong before. There's always somebody willing to show they can open a file and add a couple of variables. I now stand humbled and corrected, and suggest that we re-write the FAQ to read.... "....Don't bother attempting anything for yourself, just post your issue and someone will come forth with the code"
That having been said, the code looked quite tidy I must say.
http://www.cprogramming.com/cboard/s...threadid=17312
How do I add a loop that adds the sum of the scores?
Everytime I do it, something goes wrong?
Is it even possible or do I need to use an array?
Do you mean add the scores to form a sum? If that's the case look at the second half of the program above. The easiest way to do this is to just open your file, read the file into an array, and then just process the array. Show me what you got.Originally posted by robjules
How do I add a loop that adds the sum of the scores?
-Disguised
I'll try that and let you know
You been helpful, thanks.
I may not get back here tonight but be sure to check back tomorrow.