hey there, I've run into somewhat of a dilemma. for a practice program I'm writing, I need to input the size of an array and on the next line, I need to input the elements of that array.The input needs to look like something like this.
10 //size of array (this will vary)
1 8 5 7 5 5 7 9 4 8 //the elements of that array (this will too)
The first input is the size of an array which will be dynamically allocated and the series of numbers below will be the contents of each element, respectively.
Does anyone know how I would be able to do this? I was going to simply use a for loop, but I would end up doing the input like this:
1
8
5
7
5
5
7
9
4
8
And the question doesn't want me to do such a thing.
cin doesn't care. Try writing all the numbers in one line separated by whitespaces and only the pressing [enter]. It will work.
Sure you could force the user to enter them all in one line, but it's complicated and unnecessary (first getline then put that input to stringstream and then use operator >>).
The annoyance I ran into was using cin and getline together, I had to use cin.ignore() to get getline to work properly, and I think I ended up getting strange errors, so I just used getline for everything and then jammed them into their respective variables using a stringstream.
Here is another question, would this be a good way of getting user input from now on? One of my biggest unanswered questions from my first c++ class was getting user input. I was always able to control which number they put in if the variable called for a number, but if you entered a letter or something like that, it just went nuts.
You really didn't need to to that. Not that it matters.. By the way, another way to do this would be firtly cin >> a number then call cin.peek(). if peek() returns a '\n' (and if that wasn't your last number) the numbers are in few lines. Otherwise it's in one line.
The problem with the method I suggested before is that it is hard to check for errors that way. You probably have to count elements in stringstream or something. This method allows you to print "input must be in one line!" error message easily.