bulls and cows

I have a question for you guys, I have provided this code and it works perfectly, But I have a doubt. In lines 31/32(approx.), I have commented a while loop on the right hand side. The thing is if I use that while loop to push the data into the vector, instead of the for loop, the program breaks, somehow the "cin" or something gets carried forward or what happens I have no idea.(You can try for yourself). So Is there some peculiarity of "cin" that I am not aware about.

Thanks for your help in advance.

P.S: I break out-of-the commented while loop by using ctrl-z and enter or entering '|' and then enter.




#include<iostream>
#include<conio.h>
#include<vector>
#include<algorithm>

using namespace std;

int main()
{
vector<int>answer;
answer.push_back(1);
answer.push_back(2);
answer.push_back(3);
answer.push_back(4);

int i=0,j=0;

int temp,bull=0,cow=0;

vector<int>user;

cout<<"Lets play \n";

do{


user.clear();
cout<<"Please enter the digits of your number:\n";




for(i=0;i<answer.size();i++) //while(cin>>temp)user.push_back(temp)
{
cin>>temp;
user.push_back(temp);
}

if(user.size()!=answer.size())
{
cerr<<"Bad input,terminating \n";
exit(1);
}


for(i=0;i<answer.size();i++)
{

if(answer[i]==user[i])
{
bull++;
continue;
}

for(j=0;j<user.size();j++)
{
if(answer[i]==user[j])
cow++;
}
}

if(bull<0 || cow<0 || bull>4 || cow>4)
{
cerr<<"Error,terminating\n";
exit(1);
}



cout<<bull<<" bull and "<<cow<<" cow\n";


bull=0;
cow=0;

}while(user!=answer);


getch();

}
Last edited on
1
2
3
4
5
6
// attempt to read exactly answer.size() values
for ( i=0; i<answer.size(); i++ )
{
  cin>>temp; // could fail
  user.push_back(temp);
}
// read as many values as cin has
while ( cin >> temp )
{
  user.push_back(temp);
}

The while would work the same (and better) if you would break after you have got answer.size() numbers.
Do u mean smthin like this, or some better way?


while(cin>>temp){
user.push_back(temp);
if(user.size()==4)
break;
}

It would be gr8, if u cud also tell me tht why my while loop was breakin the program, even after exiting frm it using '|'.
while ( cin >> temp ) will loop as long as it succeed in reading an integer. When it finds '|' it will fail and the failbit will be set. As long as the failbit is set all read operations from cin will fail, so next time you enter the loop it will leave the loop right away.

To restore cin so that you can read from it again you will have to clear the error flags. cin.clear();
You also need to remove '|' from cin. To remove one character you can do cin.ignore();.
To remove the whole line you can do cin.ignore(numeric_limits<streamsize>::max(), '\n');.
Last edited on
The while loop does not "break" program. It just does not do what you expect it to do.

user.size() < answer.size() && cin >> temp
thanks a lot for your replies.

Cheers.
Topic archived. No new replies allowed.