简体   繁体   中英

C++ program not entering a for loop using vector

I was practicing with vector, I wanted to push an element using push_back(); using a for loop, but the program doesn't even enter the for loop, help!!!

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    cout << "check ";
    int val;
    vector<char> vec;
    cout << "check " << endl << "Its in the game";
    //those two "check" were to confirm if the program is even running and is it a 
    problem while declaring the vector 

    for(int i = 0; i < vec.size(); i++){
      
      cout << "enter element for vector" << endl;
      cin >> val;
      vec.push_back(val);
      
    }
}

 

Your vector is empty. The for loop starts at zero, which is not less than zero, so the for loop never runs.

Your vector is literally empty, which means vec.size() is 0.So It will never enter the loop. If you know what your vector size is gonna be, you should define it as

std::vector<int> vec(vec_size);
for(int i=0;i<vec_size;++i)
{
    //whatever.....
}

Or you could have used a while loop.

while(std::cin>>val)
{
    //do your thing....
}

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