Having trouble with a code from Accelerated C++

So I ordered a few books to start learning C++ and so far so good except for one thing. The example code that is in Ch 3 of Accelerated C++ doesn't seem to work properly.

#include <iomanip>
#include <ios>
#include <iostream>
#include <string>

using namespace std;

int main() {
cout << "Please enter your first name: ";
string name;
cin >> name;
cout << "Hello, " << name << "!" << endl;

cout << "Please enter your midterm and final exam grades: ";
double midterm, final;
cin >> midterm >> final;

cout << "Enter all your homework grades, "
"followed by end-of-file: ";

int count = 0;
double sum = 0;

double x;

while (cin >> x) {
++count;
sum += x;
}

streamsize prec = cout.precision();
cout << "Your final grade is " << setprecision(3)
<< 0.2 * midterm + 0.4 * final + 0.4 * sum / count
<< setprecision(prec) << endl;

return 0;
}

It is supposed to allow me to enter some grades from the midterm & final tests as well as some homework grades and then calculate them.

The program gets to the part where I can type in the midterm and final grades (which I do) and then it just does the cout's.

I suspect it has to do with "while (cin >> x)" because it doesn't let me input the homework grades.
Last edited on
Try flushing the buffer with cin.ignore(); function right before the cout statement.

Aceix.
1
2
cout << "Enter all your homework grades, "
"followed by end-of-file: ";



There are two strings here. Consider removing a quotation mark or inserting the << operator between the two.

 
cout << "Enter all your homework grades,  followed by end-of-file: ";

or

 
cout << "Enter all your homework grades, "<<"followed by end-of-file: ";
I do not see something wrong in the program. It seems that you are entering invalid data.
After entering homework grades press ENTER and only after that press Ctrl + Z
Ah alright. I WAS entering the data in wrong. Thx vlad and everyone else who helped.

Was a horribly stupid mistake lol. I guess it's part of learning how programming works though.
Topic archived. No new replies allowed.