In the assignment2.txt file, it contains data such as this:
12 49 22 12 <eof>
I wanted to copy that data to another file to final.txt.
In the program, it displays such as this.
1 2
|
assignment2.txt created.
12
|
When it is supposed to display like this.
1 2
|
assignment2.txt created.
12 49 22 12
|
The contents in the final.txt are like this. It is missing integer 12.
The code:
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 54 55 56 57 58 59
|
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string line, arr2[2][2];
int i, j;
string content = "";
ofstream wfile_1("assignment2.txt"); // writing assignment2.txt
if (wfile_1.is_open()) {
wfile_1 << "12 49 22 12 <eof>"; // the contents of assignment2.txt
cout << "assignment2.txt created." << endl;
}
else {
cerr << "Error while writing to assignment2.txt!";
}
wfile_1.close();
ofstream wfile_2("final.txt");
if (!wfile_2) {
cerr << "Error creating final.txt!";
}
ifstream rfile_1("assignment2.txt"); // reading assignment2.txt
if (rfile_1.is_open()) {
// reads the numbers from the file
rfile_1 >> line;
cout << line;
cout << endl;
/*for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
wfile_2 << arr2[i][j];
cout << arr2[i][j];
}
}*/
}
else {
cerr << "Error while reading assignment2.txt!";
}
cout << endl;
for (i = 0; rfile_1.eof() != true; i++) { // get content of infile
content += rfile_1.get();
}
i--;
content.erase(content.end() - 1);
rfile_1.close();
wfile_2 << content;
wfile_2.close();
}
|
What is it that I did wrong?
Last edited on
same code, just reverse it. myfile <<line[i][j] writes. You may need to add the spaces...
myfile << line[i][j] << " ";
youll need to make an ofstream instead, though. You can't write to ifstream.
Last edited on
In the text file, it writes nothing. The data disappears. Whats going on here?
what writes nothing? All you posted was a file reader.