Exception thrown when trying to print only first n elements of vector

I can't seem to figure this out. I basically want to first prompt the user how many elements they want, then allow them to input numbers like so:
1
2
5
1 2 3 4 5 6 7

for an output of
 
1 2 3 4 5

in order to generate an array, which will then print out up until the number of elements specified by the user. Here is what I have so far.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
	vector<int> a;
	int n;
	cin >> n;

	while (cin && cin.peek()!='\n') {
		int input;
		if (cin >> input)
			a.push_back(input);
	}	

	for (int i = 0; i < 4; i++)
		cout << a.at(i) << ' ';

	

	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	string y;
	getline(cin, y);
	return 0;
}

It seems to completely ignore my first cin altogether, and then freaks out because the vector is smaller than the amount of elements I inserted. I don't understand why it doesn't first prompt me for N, then prompt me for the element values of the vector, then print them.

What would be another way to use cin to instead prompt the user for exactly N values?
Last edited on
It's not ignoring the input, but you're not using the value of n for anything. How do you expect the computer to know what n is supposed to mean?
I don't understand why it doesn't first prompt me for N
What makes you think it's not prompting you? The code as you've written it will not display any feedback to you or print any requests for data, it will just accept input and then write it to your variables.

On line 18 you loop up to i == 4, even though you have no idea how many values the user actually entered. Even if we assume that the rest of your code works, what happens with this loop if the user enters 3 as the first number?
The code should look like this. I was messing around and forgot to change it back.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
	vector<int> a;
	int n;
	cin >> n;

	while (cin && cin.peek()!='\n') {
		int input;
		if (cin >> input)
			a.push_back(input);
	}	

	for (int i = 0; i < n; i++)
		cout << a.at(i) << ' ';

	

	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	string y;
	getline(cin, y);
	return 0;
}


Basically I wanted to use n to iterate the printer loop.
You should also #include <limits>

Explain what you're trying to by using cin.peek() != '\n'?
That's making the request in your first post impossible. Once the user presses Enter after typing 5, cin.peak() will equal '\n'.

Explain exactly what restriction/validation is required when the user inputs data.
Are you trying to make the input stop after the user presses enter?

Is the following acceptable?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <vector>
#include <string>
#include <limits>
#include <algorithm> 

int main() {
	using namespace std;
 
	vector<int> data;
	vector<int>::size_type n;
	cin >> n;

	do
	{
		int input;
		if (cin >> input)
			data.push_back(input);
		else
			break;
	} while (cin && cin.peek() != '\n');

	for (int i = 0; i < std::min(n, data.size()); i++)
		cout << data.at(i) << ' ';

	// Ugh... just use a proper command window...
	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	string y;
	getline(cin, y);
	return 0;
}


input:
5           
1 2 3 4 5 6 7      


output:
1 2 3 4 5 

Last edited on
You are exactly right, I want the input to stop when the user presses enter. So the reason I'm having issues is because I hit enter for the first cin and the loop doesn't even run because cin.peek() = '\n'?

Could you explain what you did with n? vector<int>::size_type n; and then later
i < std::min(n, data.size()). This part has me a little confused and it solved the error I was having issues with.

Also why did you use a do while vs. a while? What do you mean by "a proper command window?"

Thank you!
Last edited on
In your original code, first you make the user cin >> n;
You intend to have them to press enter here, but that makes cin.peek() == '\n' right from the start, invalidating your while loop.

To alleviate this, I changed it to a do-while loop, so that it will always ask for the set of numbers to input at least once, until the user presses enter again.

std::vector::size_type is the proper way to get the type that vector::size() returns. It is necessary that both things being compared in std::min are the same type, so this limits any ambiguity there. In other words, std::min(int, std::vector::size) is not valid.

The reason I used std::min is the reason that helios spoke about. What if you set your first number (the size) to 5, but then input 4 elements, and then pressed enter? Your loop would try to go out of bounds. Therefore, the std::min is necessary to stay in bounds -- it returns the smaller number of the two (the actual size of the vector vs. the size you input at the beginning).

The premise of your code is quite strange. Instead of a while loop, I would just do a for loop to get n elements (you can set the size of the vector in advance), and then print those n elements. Regardless of how many times the user presses enter. And use proper prompts, like "Enter the size of your data". Much less confusing.

What do you mean by "a proper command window?"
You dedicate three lines towards an ugly hack to get the console window to stay up so that you can see the output of your program. This... works, but depending on your IDE, you should be able to make the command prompt stay open after the program ends, or just run the program through an actual command-line window/terminal. If you do this, you won't have to worry about ugly hacks like that.
Last edited on
Wow Ganado thank you for the great reply! Makes a lot more sense now thank you. I used the while loop because I wanted the ability for the user to input more elements than were required.
Topic archived. No new replies allowed.