creating an output file

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.

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  #include <iostream>
#include <fstream>
using namespace std;


int main()

{

	ofstream newfile;
	ifstream inputFile;
	int num;


	newfile.open("evenNumbers.txt");
	inputFile.open ("numbers.txt");

		
	{
	while (inputFile >> num)

	cout <<num<< endl;
	}

	inputFile.close();

	{
	if (num % 2 == 0)
	
	newfile << num;
	}
	newfile.close();
	




	return 0;
}
First of all. Your brackets are weird.

1
2
3
4
5
6
7
8
9
10
11
12
13
{
	while (inputFile >> num)

	cout <<num<< endl;
	}

	inputFile.close();

	{
	if (num % 2 == 0)
	
	newfile << num;
	}


They should start after not before, like this -

1
2
3
4
5
6
7
8
9
10
11
12
while (inputFile >> num)
        {
	    cout <<num<< endl;
	}

	inputFile.close();

	
	if (num % 2 == 0)
	{
	      newfile << num;
	}


Also, your problem is that, you only tell it to put one of the numbers in the new file, with the if statement. use a loop instead.
What would the correct loop look like? I can't figure this out?
1
2
3
4
5
6
7
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.
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
26
27
28
29
30
int main()
{
  ofstream newfile;
  ifstream inputFile;
  int num;
  newfile.open("evenNumbers.txt");
  inputFile.open ("numbers.txt");
		
  {
    while (inputFile >> num)
    {
      cout <<num<< endl;
    }

  }

  inputFile.close();

  {
    if (num % 2 == 0)
    {
      newfile << num;
    }

  }

  newfile.close();

  return 0;
}









overwrite num every time

this is where you see every value





only one integer is still in memory, in num

if the one and only value is even ...
Topic archived. No new replies allowed.