Determining even/odd numbers from .txt file

I am trying to extract the numbers from Numbers.txt, and then put them in the correct file, either Odd.txt or Even.txt, depending on what they are. And I have gotten to a point where I am not sure what to do; right now it just reads Numbers.txt and then the program ends. Any help would be appreciated. Thanks in advance!

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <fstream>
#include <string>
#include<iomanip>
using namespace std;

int main() {

fstream file1;
fstream file2;
fstream file3;

file1.open("Numbers.txt");
file2.open("Even.txt");
file3.open("Odd.txt");

if(file1.fail()){
	cout << "Error opening file";
}

int content;

while (!file1.eof()){
	file1 >> content;
	cout << content << "\n";

	if(content % 2 == 0){
		file2 >> content;
		
	}
	if(content % 2 != 0){
		file3 >> content;
	}
}
file1.close();

int content2;
while(!file2.eof()){
	file2 >> content2;
	cout << content2 << "\n";
}
file2.close();

int content3;
while(!file3.eof()){
	file3 >> content3;
	cout << content3 << "\n";
}

file3.close();
system("pause");
return 0;
}
Last edited on
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
#include <iostream>
#include <fstream>

int main()
{
    const char input_file[] = "Numbers.txt" ;
    const char even_numbers_file[] = "Even.txt" ;
    const char odd_numbers_file[] = "Odd.txt" ;

    {
        std::ifstream input(input_file); // input stream
        std::ofstream even(even_numbers_file); // output stream
        std::ofstream odd(odd_numbers_file); // output stream

        int content;
        while( input >> content ) // canonical
        {
            if( content % 2 == 0 ) even << content << '\n' ;
            else odd << content << '\n' ;
        }
    } // destructors close the files

    std::cout << "file: " << even_numbers_file << " contains:\n"
              << std::ifstream(even_numbers_file).rdbuf() ;

    std::cout << "file: " << odd_numbers_file << " contains:\n"
              << std::ifstream(odd_numbers_file).rdbuf() ;
}
That works brilliantly, such a big help! Thank you JL
Topic archived. No new replies allowed.