skip to Main Content

The question may seem stupid, but I don’t understand why when compiling this code in visual studio, when you fill in the vector and press enter, the numbers contained in the vector are not displayed, the code seems to look correct, maybe this is due to some environment settings, tell me Please.


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

int main() {
    int x;
    vector<int> my_vector;
    while (cin >> x) {
        my_vector.push_back(x);
    }

    for (auto p : my_vector) {
        cout << p << " ";
    }
    return 0;
}

I tried compiling this code in Visual Studio 2022 and Visual Studio 2019

2

Answers


  1. Well, you also have to go out of the loop or programmatically, break the loop.

    This is the fixed version of the code

    #include <iostream>
    #include <vector>
    #include <string>
    
    int main() {
        std::string x;
        std::vector<int> my_vector;
        while (true) {
            std::cin >> x;
            if (x == "") break;
            else
            {
                try
                { my_vector.push_back(std::stoi(x)); }
                catch (std::invalid_argument)
                { std::cerr << "Invalid integer!n"; }
                catch (std::out_of_range)
                { std::cerr << "Integer too large!n"; }
        }
    
        for (auto& p : my_vector) {
            std::cout << p << " ";
        }
        return 0;
    }
    
    Login or Signup to reply.
  2. not to enter a string and then convert it to integers

    Here is another solution.
    But, when entering a string that starts with a number and ends with other characters, the number part will be push_back. Eg. cin: 1qwe123. Get: 1, ignore qwe123.

    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main() {
        int x;
        vector<int> my_vector;
    
        while (cin >> x) {
            if (cin.fail()) {
                cin.clear();         
                cin.ignore(1000, 'n'); 
                break;               
            }
            my_vector.push_back(x);
        }
    
        for (auto p : my_vector) {
            cout << p << " ";
        }
    
        return 0;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search