Using push_back for entering values into vector

Hi,

I'm trying to input double values into vector but am running into trouble.

When I use the following code, it ignores everything after asking for the inputs for the coefficients and does not let me enter in a value for "tol" and ends the program.

But when I take out the vector part of the code, I'm able to input everything that's left.

This is part of a bigger code that I'm working on but I stripped it down because the code wouldn't process due to this problem.

Thank you in advance!!

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
  int main()
{
	cout << "Enter n, the degree of the polynomial: " << endl;
	int n;
	cin >> n;

	cout << "Do you want every iteration to report? y or n" << endl;
	char response;
	cin >> response;

	cout << "Enter in coefficients. " << endl << "[";
	vector<double> coeff;
	double input;
	while (cin >> input)
	{
		coeff.push_back(input);
	}
	cout << response << endl;


	cout << "Enter threshold. " << endl;
	double tol;
	cin >> tol;

	double x = tol + n;
	cout << x << endl;


}
 
while(cin << input)


Think about the circumstances that would make this while statement end?
Hmm I am now currently trying a do-while loop instead but not sure ...

1
2
3
4
5
6
7
8
vector<double> coeff;
	cout << "Enter coefficients separted with spaces and end: " << endl << "[";
	double input;
	do 
	{
		cin << input;
		coeff.push_back(input);
	} while (cin.good())
You don't need that do while. Try this out.

*You also have to put #include<vector> if you want to work with vectors.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<iostream>
#include<vector>
using namespace std;

int main()
{
	cout << "Enter n, the degree of the polynomial: " << endl;
	int n;
	cin >> n;

	cout << "Do you want every iteration to report? y or n" << endl;
	char response;
	cin >> response;

	
	vector<double> coeff;
	double input;
	char choice_2;
	bool choice = true;

	while (choice)
	{
		cout << "Enter in coefficients: ["; cin >> input;
		coeff.push_back(input);
		cout << "Enter more coefficients?"; cin >> choice_2;
		if(choice_2 == 'Y' || choice_2 == 'y')
			choice = true;
		else 
		{
			cout << "Completed entering coefficients..." << endl;
			choice = false;
		}
		
			
	}
	cout << response << endl;


	cout << "Enter threshold. " << endl;
	double tol;
	cin >> tol;

	double x = tol + n;
	cout << x << endl;

	system("pause");


}
Last edited on
Thank you thank you thank you thank you!!

I realized when I ran the program, I was entering the coefficients like "0 1 2 3 4]" and then pressing enter.

But this works when I put in one coefficient at a time and pressing enter!!

Topic archived. No new replies allowed.