I wasn't exactly sure why variables were declared inside the ()'s for main.
int main( int argc, char* argv[] ) |
Command line arguments. One can start programs from command line / terminal / shell script. Some programs accept arguments. E.g.
dir
dir C:\Users
dir /S C:\Users |
(the MS 'dir' is not actually a "program", but the concept of (optional) arguments is similar. For that reason the standard has more than one signature for main():
1 2
|
int main()
int main(int, char**)
|
That example program, however, does not use the function parameters at all. A compiler should/could show a "warning: unused" message.
I'm assuming std::numeric_limits sets it so that only numerical values are able to be entered but as of now I need to read up on that. |
The secret of that is in the
cin.ignore
. It takes a number and a character. It discards characters from stream, until it either sees the <character> or has discarded <number> characters. Two ending conditions: whichever comes first.
The
std::numeric_limits<std::streamsize>::max()
is a very big number. It is quite likely that the call of std::ignore will return on encountering <character> which is
newline.
The while-loop (yes, while and for are "loops", you are "looping", or "iterating") will repeat as long as:
1. input fails
or
2. input is too small
or
3. input is too large
If input fails, then 'a' does not have a valid value. Due to the nature of logical OR, there is no need to evaluate the second condition. Logical AND is similarly "lazy"; it will not evaluate both conditions, if the first one is false (which alone ensures that entire AND is false).
In your case it is enough to have two conditions: input is successful and 'a' is not negative.
What the while-loop in that program does is to set the value of 'a'. You just have to repeat it 10 times.
Your second attempt does have a flaw:
1 2 3 4
|
for ( double bar = 0; bar <= 9; bar++ )
{
cin >> bar; // what if I type 42 on first time? Or 7 every time?
}
|
You want the loop to repeat
exactly 10 times, no matter what (valid input) I do type. The variable that you do store the input into must be thus be different from the loop counter. In the first program you did have a separate variable; actually a whole array of them (foo).
Furthermore, the loop counter is better to be integral; floating-point math is not as intuitive as one expects.
In your first program you (could have) had essentially this construct:
1 2 3
|
double foo[10];
int bar = 7;
std::cout << bar[foo];
|
It,
bar[foo]
, is non-conventional, but legal. The foo is treated like a pointer (double*) and the operator [] can be replaced with:
1 2 3 4 5 6 7
|
bar[foo]
<=>
*(bar + foo)
<=>
*(foo + bar)
<=>
foo[bar]
|
The last version is the conventional syntax:
arrayname [ index ]