How do i get ctrl-z to stop

i know you use ctrl z to break out a loop with cin >> as its code but when i do finally press ctrl z it runs through the rest of my program and closes, it doesnt care that i have a cin.get() or a cin >>x really wanna know what im doin wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 #include <iostream>
#include <string>
#include <vector>
using std::cin; using std::cout; using std::endl; using std::string;
using std::vector;
int main()
{
	vector<int> v1;//{1,2,3,4}
	int x;
	while (cin >> x) {
		v1.push_back(x);
	}
	
	for (int i = 0; i != v1.size() - 1; ++i) {
		cout << v1[i] + v1[i + 1] << " ";
		cout << endl;
	}
	cin.sync();
	cin.get();
	cin >> x;
	return 0;
}
Ctrl-Z (on Windows; Ctrl-D on Linux) means end of stream. By pressing it you are signalling to your program that there is no more input.

The simple answer would be to cin.clear(); right after line 12.

A better answer is that you can guide the user by some careful prompts and by getting input with a function.

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
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <vector>

bool string_to_int( const std::string& s, int& result )
{
  std::istringstream ss( s );
  ss >> result >> std::ws;
  return ss.eof();
}

int main()
{
	std::vector<int> v1;

	std::cout << "Please enter integers, one per line. Press Enter twice to finish.\n> ";
	std::string s;
	while (std::getline(std::cin,s) && !s.empty()) {
		int x;
		if (!string_to_int(s,x)) std::cout << "Integers only";
		else v1.push_back(x);
		std::cout << "> ";
	}

	for (unsigned n = 0; n < v1.size() - 1; ++n) {
		std::cout << (v1[n] + v1[n+1]) << " ";
	}
	std::cout << std::endl;

	std::cout << "Press ENTER to quit.\n";
	std::cin.ignore( std::numeric_limits <std::streamsize> ::max(), '\n' );
	return 0;
} 

Hope this helps.
omg thank you, cin.clear(); works perfectly.
Topic archived. No new replies allowed.