Hello again! I was given an assignment the other day in C++ and I was suppose to use the counter and add a sentinel so the program knew when to stop.
"The file for this assignment reads a sequence of positive integers from a file (2 3 5 7 9 10 22 54 66) and prints them out to the screen together with their sum. Create the text file that can be used to input these integers and add to the program a set of instructions that provides the number of integers in the sequence. You are to assume you do not know the number of integers in the sequence."
I have been able to get everything to work except 2 things. I can't get the "2" to print out and the sentinel, "0", has been printed out. I need help with having the "2" print out and for the sentinel, "0", not to.
Here is my code:
using namespace std;
int count = 1;
int sentinel = 0;
ifstream datain ("Input.txt");
The_Sum = 0;
cout<<" | Positive Integers \n"<<endl;
datain >> Positive_Integers;
while (Positive_Integers != sentinel)
for (count = 1; count<=Positive_Integers; count ++)
The_Sum = The_Sum + Positive_Integers;
cout<<endl<<"The Sum = "<<The_Sum<<endl<<endl;
Here is my text from the file:
Thanks again guys. So far I'm enjoying this website. :)
The first thing your inner loop does is read from the file into Positive_Integers . However, the first number was already read to determine if it was a sentinel in the outer loop. So you're basically discarding the first number. The next number should be read after the current number is displayed and added to the total.
However, your inner loop isn't meaningful (in fact, it can produce erroneous output depending on the contents of the file). It can be removed entirely in favor of a single loop like so: