How to cin to a vector

后端 未结 20 2510
萌比男神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: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.

提交回复
热议问题