How to cin to a vector

后端 未结 20 2449
萌比男神i
萌比男神i 2020-11-27 14:44

I\'m trying to ask the user to enter numbers that are put into a vector, then using a function call to count the numbers, why is this not working? I am only able to count t

相关标签:
20条回答
  • 2020-11-27 15:21

    you have 2 options:

    If you know the size of vector will be (in your case/example it's seems you know it):

    vector<int> V(size)
    for(int i =0;i<size;i++){
        cin>>V[i];
     }
    

    if you don't and you can't get it in you'r program flow then:

    int helper;
    while(cin>>helper){
        V.push_back(helper);
    }
    
    0 讨论(0)
  • 2020-11-27 15:22

    The initial size() of V will be 0, while int n contains any random value because you don't initialize it.

    V.size() < n is probably false.

    Silly me missed the "Enter the amount of numbers you want to evaluate: "

    If you enter a n that's smaller than V.size() at that time, the loop will terminate.

    0 讨论(0)
  • 2020-11-27 15:24

    cin is delimited on space, so if you try to cin "1 2 3 4 5" into a single integer, your only going to be assigning 1 to the integer, a better option is to wrap your input and push_back in a loop, and have it test for a sentinel value, and on that sentinel value, call your write function. such as

    int input;
    cout << "Enter your numbers to be evaluated, and 10000 to quit: " << endl;
    while(input != 10000) {
        cin >> input;
       V.push_back(input);
    }
    write_vector(V);
    
    0 讨论(0)
  • 2020-11-27 15:25

    In this case your while loop will look like

    int i = 0;
    int a = 0;
    while (i < n){
      cin >> a;
      V.push_back(a);
      ++i;
    }
    
    0 讨论(0)
  • 2020-11-27 15:30

    As is, you're only reading in a single integer and pushing it into your vector. Since you probably want to store several integers, you need a loop. E.g., replace

    cin >> input;
    V.push_back(input);
    

    with

    while (cin >> input)
        V.push_back(input);
    

    What this does is continually pull in ints from cin for as long as there is input to grab; the loop continues until cin finds EOF or tries to input a non-integer value. The alternative is to use a sentinel value, though this prevents you from actually inputting that value. Ex:

    while ((cin >> input) && input != 9999)
        V.push_back(input);
    

    will read until you try to input 9999 (or any of the other states that render cin invalid), at which point the loop will terminate.

    0 讨论(0)
  • 2020-11-27 15:30

    If you know the size of the vector you can do it like this:

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        int n;
        cin >> n;
        vector<int> v(n);
        for (auto &it : v) {
            cin >> it;
        }
    }
    
    0 讨论(0)
提交回复
热议问题