I have encountered a problem with this task:
your input is a number and the output is from 1 to the input number. If the number is zero, the output will be nothing.
For instance your input is
5 10 3 0Your output will be
1 2 3 4 5 1 2 3 4 5 6 7 8 9 10 1 2 3
So, there are apparently three answers.
The first solution uses this:
#include <iostream>
using namespace std;
int main()
{
int x;
while (true)
{
cin >> x;
if (!x) break;
for (int i = 1; i <= x; i ++ ) cout << i << ' ';
cout << endl;
}
return 0;
}
The other two solutions replace this:
while (true)
{
cin >> x;
if (!x) break;
with this:
while (cin >> x && x)
or this:
while (cin >> x, x)
I understand the first solution, but not the other two.
Can someone help me?
The
>>operator, by convention, when applied to anistreamobject should return theistreamobject itself. So the return value ofcin >> xis thecinobject itself. When used as a Boolean, a stream object returns truthy if there are no errors in input/output.This says "while the loop successfully reads a value without errors and that value is not zero".
The comma operator is one of the more obscure pieces of C++ syntax.
a , bevaluatesaand thenband returns the result ofb, discarding the result ofa(this is assuming the comma doesn't do something else; for instance, in a function argument list the comma is part of that syntax, not its own operator). Socin >> x, xsays "do thecinpart, ignore the return value of that, and then checkx".This says "get input and run as long as the input is nonzero". Crucially, errors in the input process are ignored here.
Minor note: Technically, programmers can overload the comma operator to call an arbitrary function. So if a programmer (whose mental health we might call into question) wrote a function like
Then that function would get called by
cin >> x, x. But every C++ style guide I've ever seen recommends against ever overloading the comma operator, so this is pathological at best.