0

I am trying to compare two integer vectors. The first loop in the program is executing but the second and the third loop is not executing.

vector<int> a,b;
    int range=0;
    cout<<"Enter 1st vector."<<endl;
    for(int n=0;cin>>n;)
    {
        a.push_back(n);
    }
    cout<<"Enter 2nd vector."<<endl;
    for(int n=0;cin>>n;)
    {
        b.push_back(n);
    }
    if(a.size()>b.size())
        range=b.size();
    else
        range=a.size();
    cout<<"\nThird loop."<<endl;
    for(int i=0;i<range;i++)
    {
        if(a[i]!=b[i])
            goto here;
    }
    cout<<"\nSame vectors."<<endl;
    return 0;

This is the output.

  • 3
    Since you are asking about comparing and not about inputting please make a [mre] with suitable hard-coded sample data to demonstrate your problem, so as to avoid problems with input getting in the way. Otherwise, if input IS the problem, please ask about input, not about comparing. – Yunnosch Mar 29 '20 at 07:25
  • Can you include a running example? The second loop must read a value into `n` in order to get `0` and stop/skipping executing, so something doesn't make sense. – SomethingSomething Mar 29 '20 at 07:25
  • Does this answer your question? [How to reset std::cin when using it?](https://stackoverflow.com/questions/39282953/how-to-reset-stdcin-when-using-it) – 273K Mar 29 '20 at 07:36

1 Answers1

0

You are getting this behavior because of using cin >> n as conditional. During first loop execution it keeps returning cin (which is an instance of std::istream) which is valid non-null pointer. But when you press ctrl-z, underlying stream becomes invalid and it starts returning nullptr. Hence cin>>n in second loop evaluates to false and loop doesn't execute. Then you set range to be size of b vector which is zero so third loop doesn't execute.

Check this stackoverflow link for more detals on using cin as conditional if (cin >> x) - Why can you use that condition?

If you want to use cin as conditional in for loop, break the loop based on conditions like n == SomeSpecificEndValuerather than ctrl-z

nkvns
  • 580
  • 3
  • 5