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.
// Problem 1 = Life, the Universe.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
usingnamespace 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;
}
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++.
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