why i must remove one of the ifstreams??
whats the purpose of that?
Well, when I first saw the code, I had my own question, I saw two streams, and asked myself, "what is the purpose of that?" - so maybe you could explain why you thought it was necessary.
But let me give a proper explanation. Each stream has a special pointer which gives the current position within the file. When the stream is first opened, the position is at the very first character, that is, it is positioned at the letter 'B' Bill 87:77:80
After doing this, indata>>name; the position has moved forward, just past the end of the word "Bill". So now you are ready to read the next item, which is the number "87".
But if instead you now use the other ifstream, that is still positioned at the very start of the file, on the letter 'B'. So you try to read the number, but instead get the name "Bill". That will be very much incorrect.
and what if i want to calculate the avg and print the name of the second guy?
Well, you need to repeat this block of instructions:
1 2 3 4 5 6 7 8
indata >> name;
indata >> m1 >> a >> m2 >> b >> m3;
sum=m1+m2+m3;
avg= sum/3.0;
cout<<"name is :"<<name<<endl;
cout<<"AV. : "<<avg<<endl;
You could literally do that, add the same code all over again. But a better way is to use a loop. Now a loop repeats the same instructions over and over again until we tell it to stop. How do we know when to stop? In this case, when there is no more data. So you could do something like this:
1 2 3 4 5 6 7 8 9 10
while (indata >> name)
{
indata >> m1 >> a >> m2 >> b >> m3;
sum=m1+m2+m3;
avg= sum/3.0;
cout<<"name is :"<<name<<endl;
cout<<"AV. : "<<avg<<endl;
}
The first line here does several things: while (indata >> name)
First, it reads the name from the file. Next it checks the status of the stream indata. This evaluates to give a logical true or false. If the file was successfully read, the condition is true, so the body of the loop will execute. But if there is no more data, the read fails and the condition is false. Then the loop will terminate.
thanks man you are amazing..
i dont know how to thank you.!:) :)
but when i asked you about the second guy..!
what if i want to print his name and his avg
with out printing the name of the first and third guy with their averages ?!
is it possible ??
and one more question .. how do you do this rectangle .. i mean in your comment
your write C++ codes in a rectangle
There may be lots of different answers, depending on where you plan to take this next.
But to give an example, you could read the data using a loop as I suggested, and then test if (name == "Mike") before calculating and printing the output.
Another way would be to use a counter, an integer value which starts at zero. Each time you read another row of data, add 1 to the count. Then use if (count == 2)