I need the program to create a new file named 'evenNumbers'. My problem is that the only line that was saved in my new file was the very last one. The file is just a list of numbers and my objective is to transfer only the EVEN numbers into a new file.
while (inputFile >> num) // reads number
{
if (num % 2 == 0) // checks if number is even
{
newFile << num; // if number is even, put it in the new file
}
}
It is legal, even if unusual, to have statements in a brace block. One can, for example, to limit scope (and lifetime) of a variable:
1 2 3 4 5 6 7
int foo = 7;
{
int bar = 2 * foo;
cout << bar;
}
// bar does not exist any more, but foo does.
Control constructs, like if and while, can have one or more statements that (conditionally) execute. One statement can be alone, but many have to be in a brace block. It is legal to have only one statement in brace block. Therefore, these two are same:
1 2 3 4 5 6 7 8
// A
while (inputFile >> num) cout << num << endl;
// B
while (inputFile >> num)
{
cout << num << endl;
}
Indentation is a useful helper and most editors support it. There are naturally many styles, but some "show" more than others.