Hi, i have a file with these following numbers and i want to take it as an array and take the average, i could write this much but im getting wrong average:
34
99
12
54
79
100
3
13
17
68
93
21
46
42
83
The .eof() is not necessarily accurate way to end the loop.
Consider that each line ends with end-of-line. Even the last one:
42^M
(The ^M represents the end-of-line.)
You read the "42". You are not at the end, for there is still one whitespace character left. You try to read one more number, but there are no numbers after the 42. You fail.
Nevertheless, you think that you have got a value.
1 2 3 4 5 6 7 8 9 10
int value = 0;
size_t count = 0; // unsigned counter to show intent
while ( count < 100 && fin >> value )
{
// if we get here, then
// * the value is a valid number
// * we have got one more value
// * array still has "free" element to store the value in
}
// assert: count is the number of values AND <= 100
The fin >> value returns fin. The fin converts to true, if the input operation was successful.