Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read in user entered comma separated integers?

Tags:

c++

cin

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 dynamically allocated array (required) and make it the size the user wants.

I'm stuck on the next part. The user is expected to enter in a series of ints separated by commas such as: 1,2,3,4,5

How do I take in those ints and put them into my dynamically allocated array? I read that by default cin takes in integers separated by whitespace, can I change this to commas?

Please explain in the simplest manner possible, I am a beginner to programming (sorry!)

EDIT: TY so much for all the answers. Problem is we haven't covered vectors...is there a method only using the dynamically allocated array I have?

so far my function looks like this. I made a default array in main. I plan to pass it to this function, make the new array, fill it, and update the pointer to point to the new array.

int *fill (int *&array, int *limit) {

cout << "What is the desired array size?: ";                                  
while ( !(cin >> *limit) || *limit < 0 ) {
    cout << "  Invalid entry. Please enter a positive integer: ";
    cin.clear();
    cin.ignore (1000, 10);
}

int *newarr;                                                                            
newarr = new int[*limit]
    //I'm stuck here
}
like image 349
Ian004 Avatar asked Feb 17 '14 19:02

Ian004


1 Answers

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<class T, char sep=','>
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<class T, char sep>
std::istream& operator>>(std::istream& in, comma_sep<T,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<comma_sep<int>> istrit; //iterators from the stream
std::vector<int> 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.

like image 91
Mooing Duck Avatar answered Oct 13 '22 12:10

Mooing Duck