I am trying to get this code to split an input file into two files. I want the code to split so that one new file contains all the odd characters and the other file contains all the even characters. My code gives me no errors and it produces two new files but the two new files contain nothing in them. I am wondering what is wrong with my code(I am sure there is a lot wrong with it). I am still pretty new to programming.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void split(char sourceFile[], char destFile1[], char destFile2[]) {
int chars = 0;
ifstream sFile;
sFile.open(sourceFile);
ofstream file1;
file1.open(destFile1);
ofstream file2;
file2.open(destFile2);
while (!sFile.eof()) {
sFile.read(sourceFile + chars, 1);
cout << sourceFile[chars];
if (chars % 2 == 0) {
file1 << sourceFile[chars];
} else {
file2 << sourceFile[chars];
}
chars++;
}
}
int main() {
split("text.txt", "one.txt", "two.txt");
return 0;
}
There’s a lot wrong with it (as you said)
1) All your files are
ifstream, if you want to output to a file useofstream.2) You should not attempt to use the file names as variables for your code. Just declare a new char variable.
3) Use get not read to read single characters.
4) Test for end of file correctly.
5) Don’t close the files inside the loop, in fact don’t close the files at all, it will happen automatically when you exit the function.
6) What on earth is
chars%2 == 5about? It will never be true.Putting that together