简体   繁体   中英

for loop is not executing/working properly in c++

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;

这是输出。

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 == SomeSpecificEndValue rather than ctrl-z

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM