problem with files

i tried to solve this but i have a proplem : the q is :
but i have a problem to put every output data in a file , i don't know why plz help me, this is the q:

write a complete c++ program that opens and reads a text file named(c:\mydocs\lists) ,each line of this file contains n integer numbers ,where n is stored at the beginning of each line. your program should read these n integers in each line and write the odd integers to a file called(c:\mydocs\odd.txt) and the even numbers to file called (c:\mydocs\even.txt), the number of lines in the source file are unknown and your program should read lines until the end of the file ,there is an error message if the file dose not exist .

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
  #include<iostream>
#include<fstream>
using namespace std;
int main ()
{
	ifstream infile;
	ofstream outfile;
	infile.open("lists1.txt");
	outfile.open("odd.txt");
	
	int n;
	infile>>n;
	while(infile)
	{

		if(n%2==0){
			cout<<"even"<<endl;
		
			outfile<<n<<endl;}
			

		else if (n%2!=0){
			cout<<"odd"<<endl;
			outfile<<n<<endl;}

			
		
		
		infile>>n;
	}

	system("pause");
	return 0;
}
	
help me plz
You are outputting to the file for both odd and even numbers, get rid of line 19.
Lets say that your "mydocs.txt" containes those numbers

41 67 34 0 69 24 78 58 62 64
5 45 81 27 61 91 95 42 27 36
91 4 2 53 92 82 21 16 18 95
47 26 71 38 69 12 67 99 35 94
3 11 22 33 73 64 41 11 53 68


This program do everything you asked above

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>
# include <cstdlib>
using namespace std;

int main()
{
    ifstream in("mydocs.txt");

    int oddNumber[100],oddIndex=0;
    int evenNumber[100],evenIndex=0;

    if(in)
    {
        while(in)
        {
            int nbr;
            in >> nbr;
            if(nbr%2)
                oddNumber[oddIndex++] = nbr;
            else evenNumber[evenIndex++] = nbr;
        }

        in.close();
    }else cout << "Cannot open this file" << endl;

    ofstream oddOut("odd.txt"),evenOut("even.txt");

    for(int i=0;i<evenIndex;i++)
        evenOut << evenNumber[i] << " ";

    for(int i=0;i<oddIndex;i++)
        oddOut << oddNumber[i] << " ";

    evenOut.close();
    oddOut.close();

    return 0;
}


now the odd.txt containes
41 67 69 5 45 81 27 61 91 95 27 91 53 21 95 47 71 69 67 99 35 3 11 33 73 41 11 53


and the even.txt containes
34 0 24 78 58 62 64 42 36 4 2 92 82 16 18 26 38 12 94 22 64 68 68


Hope that helps
Last edited on
well thanks alot you are amazing
Topic archived. No new replies allowed.