Okay, so I have a lab exercise where I have to modify a program I already did in a previous exercise. I had to build a program which prompts for and reads a one-digit number, then adds the numbers from zero to that number (inclusive), and prints the sum. I then had to modify it so that the summation process repeats until a negative digit is read. Here is what I have:
// Program SumDigits prompts for and reads a one-digit number.
// Values between 0 and the digit (inclusive) are summed.
#include <iostream>
using namespace std;
int main ()
{
int counter; // Loop-control variable
int sum; // Running sum
int digit;
cout << "Enter a positive one-digit number; press return. The processing will stop if the number entered is negative."
<< endl;
cin >> digit;
while (digit >= 0);
{
counter = 0;
sum = 0;
while (counter <= digit)
{
sum = sum + counter;
counter++;
}
cout << "Sum of digits between 0 and "
<< digit << " is " << sum << endl;
}
return 0;
}
I need to modify this program so that the values will be read from a file called "digits.dat", which I have already created, and the summation process should still be repeated until a negative digit is read or until the end of the file. Here is my incorrect program:
// Program SumDigits prompts for and reads a one-digit number.
// Values between 0 and the digit (inclusive) are summed.
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ifstream inData;
inData.open("digits.dat");
int counter; // Loop-control variable
int sum; // Running sum
int digit;
cout << "Enter a positive one-digit number; press return. The processing will stop if the number entered is negative."
<< endl;
inData >> digit;
while (inData && digit >= 0);
{
counter = 0;
sum = 0;
while (inData && counter <= digit)
{
sum = sum + counter;
counter++;
}
cout << "Sum of digits between 0 and "
<< digit << " is " << sum << endl;
inData.close();
}
return 0;
}
I get the prompt to enter a number, but it does not read the data from the file like I want it to. Can someone please help me with this? I would appreciate it very much!
// Program SumDigits prompts for and reads a one-digit number.
// Values between 0 and the digit (inclusive) are summed.
#include <iostream>
#include <fstream>
usingnamespace std;
int main ()
{
ifstream inData;
inData.open("digits.dat");
int counter; // Loop-control variable
int sum; // Running sum
int digit;
cout << "Enter a positive one-digit number; press return. The processing will stop if the number entered is negative."
<< endl;
inData >> digit; /// This code reads the data in the file. You only read from the file once.
/// Should be in a loop.
while (inData && digit >= 0);
{
counter = 0;
sum = 0;
while (inData && counter <= digit)
{
sum = sum + counter;
counter++;
}
cout << "Sum of digits between 0 and "
<< digit << " is " << sum << endl;
inData.close(); /// Don't close the file inside the loop.
}
return 0;
}