Life, the Universe, and Everything

our program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely… rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.

Input:
1
2
88
42
99

Output:
1
2
88

Here is my code below! I successfully wrote the program to output the number that the user imputted. Is there a way to write it so that after the user imputs 42, it doesnt output the other numbers that the user imputs, like the example above? I want the user to be able to imput numbers after they imput 42, but the program does not output those numbers. Right now, it just closes the console once the user imputs 42.
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
// Problem 1 = Life, the Universe.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	int imput;
	
	cin >> imput; //reads the first number 

	while(imput != 42) //Print out number that we just checked is NOT 42
	{
		cout << imput << endl;
		cin >> imput;
	}
	

	return 0;
}

> I want the user to be able to imput numbers after they imput 42,
> but the program does not output those numbers.

This is one way:

1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
    int input ;
    while( std::cin >> input && input != 42 ) std::cout << '\t' << input << '\n' ;
    while( std::cin >> input ) ;
}

thanks a lot! I understand it

edit: I have a quick question

Why does adding while (cin >> imput); stop processing imput after reading 42? Is there an "after" function in c++, so like "after this happen this happens"? That might be stupid sounding, but im just new to c++.
Last edited on
closed account (18hRX9L8)
Because it is a completely different loop that does nothing but read in random input.
Last edited on
The expression std::cin >> input && input != 42 evaluates to true if
a. We have succeeded in reading an integer
b. And (&&) the integer is not equal to 42

Otherwise it evaluates to false

1
2
while( std::cin >> input && input != 42 ) // as long as the expression evaluates to true
     std::cout << '\t' << input << '\n' ; // perform this action 


The first loop is exited from when the expression evaluates to false.

And we carry on with the next loop:
1
2
while( std::cin >> input ) // as long as we have succeeded in reading an integer 
    ; // do nothing 


Awesome! thanks for that explanation! Until nextime
Topic archived. No new replies allowed.