How to read in user entered comma separated integers?

后端 未结 9 553
轮回少年
轮回少年 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:54

    All of the existing answers are excellent, but all are specific to your particular task. Ergo, I wrote a general touch of code that allows input of comma separated values in a standard way:

    template
    struct comma_sep { //type used for temporary input
        T t; //where data is temporarily read to
        operator const T&() const {return t;} //acts like an int in most cases
    };
    template
    std::istream& operator>>(std::istream& in, comma_sep& t) 
    {
        if (!(in >> t.t)) //if we failed to read the int
            return in; //return failure state
        if (in.peek()==sep) //if next character is a comma
            in.ignore(); //extract it from the stream and we're done
        else //if the next character is anything else
            in.clear(); //clear the EOF state, read was successful
        return in; //return 
    }
    

    Sample usage http://coliru.stacked-crooked.com/a/a345232cd5381bd2:

    typedef std::istream_iterator> istrit; //iterators from the stream
    std::vector vec{istrit(in), istrit()}; //construct the vector from two iterators
    

    Since you're a beginner, this code might be too much for you now, but I figured I'd post this for completeness.

提交回复
热议问题