How to read in user entered comma separated integers?

后端 未结 9 555
轮回少年
轮回少年 2020-12-07 02:14

I\'m writing a program that prompts the user for:

  1. Size of array
  2. Values to be put into the array

First part is fine, I create a dynamica

9条回答
  •  醉酒成梦
    2020-12-07 02:32

    Victor's answer works but does more than is necessary. You can just directly call ignore() on cin to skip the commas in the input stream.

    What this code does is read in an integer for the size of the input array, reserve space in a vector of ints for that number of elements, then loop up to the number of elements specified alternately reading an integer from standard input and skipping separating commas (the call to cin.ignore()). Once it has read the requested number of elements, it prints them out and exits.

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main() {
        vector vals;
        int i;
        cin >> i;
        vals.reserve(i);
        for (size_t j = 0; j != vals.capacity(); ++j) {
            cin >> i;
            vals.push_back(i);
            cin.ignore(numeric_limits::max(), ',');
        }
        copy(begin(vals), end(vals), ostream_iterator(cout, ", "));
        cout << endl;
    }
    

提交回复
热议问题