-
confused with cin.get()
hi,
Just c the code below:
Code:
int main()
{
vector<int> ratings(5);
for(int i=0; i<5; i++)
{
cout<< "enter rating:";
cin >> ratings[i];
}
for(i=0; i<5; i++)
{
cin.get();
cout<< ratings[i];
// cin.get();
}
}
in the second "for" loop moving "cin. get" after cout<< ratings(i.e deleting the cin.get above cout and adding cin after cout) changes the way output looks.
In the first case (when cin.get is above cout) the ratings are displayed one after the other on hitting the enter key. In the second case(when cin.get is after cout) if I enter rating say, 1,2,3,4,5 then the output shows 12 and then waits for the enter key.
Why shud this happen??
Best Regards,
Shal
-
Code:
int main()
{
vector<int> ratings(5);
for(int i=0; i<5; i++)
{
cout<< "enter rating:";
cin >> ratings[i]; // last '\n' is stored on the buffer
}
for(i=0; i<5; i++)
{
cout<< ratings[i];
/*Start to out put first item,
then '\n' stored in the buffer is passed to the
next statement cin.get() */
cin.get(); //received the '\n' from buffer at the second looping
//the loops works normally from the third item.
}
}
As I explained, the '\n' is stored in buffer result from the last inputting the last item for the vector. Try to ignore the '\n' at the end of the first loop. It will ignore that '\n' when the next cin.get() is called.
Code:
int main()
{
vector<int> ratings(5);
for(int i=0; i<5; i++)
{
cout<< "enter rating:";
cin >> ratings[i]; // last '\n' is stored on the buffer
}
cin.ignore(1000,'\n'); //ignore the last enter
for(i=0; i<5; i++)
{
cout<< ratings[i];
cin.get();
}
-
Thanks for ur response!!! I thought there was some \n getting stored in the buffer but i didn't knew how to ignore it