Ch4.Q1.Drill

Please explain how I can filter the "|" character value and terminate. I think the rest of the code is right, but filter a non int type such as '|' makes no sense. If I enter in '|' the program will not store this in type int.

Q: 1. Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the program when a terminating '|' is entered.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

#include"../../std_lib_facilities.h"

int main()
{
	int val1 = 0;
	int val2 = 0;

	cout << "Please enter two integer values.\n";
	while (cin >> val1 >> val2)
	{
		cout << val1 << " " << val2<<'\n';
		
	}
	return 0;
}
Last edited on
Currently any non numeric value will end the loop (because cin returns false in that case). The invalid character will remain in the stream. If you clear the error (cin.clear();) you can read what caused it, e.g.:
1
2
3
4
5
6
7
8
9
10
11
	cout << "Please enter two integer values.\n";
	while (cin >> val1 >> val2)
	{
		cout << val1 << " " << val2<<'\n';
		
	}
	cin.clear();
	std::string str;
	getline(cin, str);

	cout << "End: " << str <<'\n';
You could have continued discussion in the previous thread: http://www.cplusplus.com/forum/beginner/188321/

Presumably the operation must continue until a proper terminating character is found. That means a loop. By line 11 of coder777's example we know whether the "inner loop" was interrupted by '|' in the input.
If no, we should restart from line 1. If yes, the "outer loop" can quit/break.

A do while seems intuitive as the outer loop, doesn't it?
Topic archived. No new replies allowed.