It works fine for me. A couple of suggestions though:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
#include <string>
using namespace std;
int main() // main _always_ returns int
{
int total, count, mark;
string name; // In the US, at least, people cannot be named a number.
total = count = 0; // If 'count' starts at zero it will stop at ten. See [1].
while (count < 10)
{
cout << "Enter student " << count+1 << "'s name: ";
getline( cin, name ); // See [2]
cout << "Enter student " << count+1 <<"'s grade: ";
cin >> mark;
cin.ignore( numeric_limits<streamsize>::max(), '\n' ); // See [2]
total = total +mark;
++count;
}
// See [3]
cout << "The total is " << total << endl;
cout << "The average is " << (double)total /count << endl;
return 0;
}
| |
[1] Remember, the averages is "total / count", but if you start counting at zero then (count >= 10) will only be true when count == 11. However, you only have 10 students. This is what you call a "fencepost" or "off by one" error. So I changed it to start counting at zero and stop when count becomes ten. The other way to fix it would have been just to subtract one from count after the loop terminates...
[2] User input is a tricky thing, but one fairly constant truth is that no matter what you ask the user to input he will have to press ENTER after every input. You should design your programs with this in mind and always get that '\n' (newline or ENTER) out of the input stream.
In the first case, the user was asked to input a string. Strings may have spaces in them, so I used getline(), which reads everything typed until the '\n', stores it in the string, then reads and throws away the '\n'.
In the second case, you used the >> operator to read a number from the stream. The >> operator only reads things it is asked to. In this case, a number. So the '\n' is still sitting there, and we have to get rid of it before the next time we ask the user for input. That's what the cin.ignore() statement does: ignore (that is, read and throw away) everything up to and including the next '\n' in the input.
[3] I moved the stuff that displayed both the total and the average out of the loop. I could have left it in the loop --it doesn't matter. Well, except that I only wanted to display it once, after all input was received, instead of ten times, once after _every_ input is received.
Your compiler may accept specifying main() without a return type, but that is non-standard. In C++, you _must_ specify "int main()" or "int main(int argc, char**argv)".
Also, for interest, in the USA you are allowed to name your poor kid just about any stupid thing you can think of. Except a number. Weird trivia for you.
Hope this helps.