So I'm working on a simple file manipulating project where I need to append a new text on a single line, so, to visualize that suppose I have a text file called main.txt
and in that file it contains a row of text that looks like this:
[AB]
1
2
Now that lets say I want to add another text: [CB]
& 4,5
, then I want the updated file to looked like this:
[AB] [CB]
1 4
2 5
But turns out it looked like this instead:
[Ab]
1
2
[CB]
4
5
Here's what I've tried so far
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
int main() {
std::ofstream file("C:\users\USER\Documents\CPPPRoject\nice.txt",std::ios::out|std::ios::app);
file << "\t" << "[CB]" << "\n";
file << "\t" << 4 << "\n";
file << "\t" << 5 << "\n";
return 0;
}
CodePudding user response:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// we have only 1 column in this example and also we have only 2 rows of data
int columnCount = 1, dataRows = 2;
string newColumnName;
int data1, data2;
cout << "enter the column name: ";
cin >> newColumnName;
// getting the new datas based on the amount of the rows
int *data = new int[dataRows];
for (int i = 0; i < dataRows; i )
cin >> data[i];
// opening the orginal.txt and pasting it into copy.txt with new data
fstream original, copy;
original.open("original.txt", ios::in);
copy.open("copy.txt", ios::out);
// copy & paste the columns
string inStr;
for (int i = 0; i < columnCount; i )
{
original >> inStr;
copy << inStr << " ";
}
copy << newColumnName << "\n";
// copy past the columns
int inData;
for (int i = 0; i < dataRows; i )
{
for (int j = 0; j < columnCount; j )
{
original >> inData;
copy << inData << " ";
}
copy << data[i] << "\n";
}
original.close();
copy.close();
// deleting the original and renaming the copy.txt
remove("original.txt");
rename("copy.txt", "original.txt");
return 0;
}
this is a simple code to add a column to the text file which only have 1 column of data , for doing it to larger file you can adjust columnCount
and dataRows
.
sample test of code :
original.txt before running the code
[AB]
5
6
program inputs ( column name and new data to insert)
enter the column name: [CD]
1 2
original.txt file after execution of the code
[AB] [CD]
5 1
6 2