So I have some data in a csv file suppose:
name,age,number
name2,age2,number2
name3,age3,number3
I have to insert a new data at a specific position which is given by the user. Lets say user says line 2 so then the updated data would be:
name,age,number
newname,newage,newnumber
name2,age2,number2
name3,age3,number3
Now I know to do so I'd have to copy the entire data to a new file and then make changes and then overwrite the data in the original file. How would I create a line so that the user can input data at that specific position?
So far I have done this but I don't know how to insert data at specific position in a file
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char names[20], newname[20], contact[20];
int age;
cout << "Enter name : ";
cin.ignore();
cin.getline(newname, 19);
cout << "Enter age : ";
cin >> age;
cout << "Enter contact no : ";
cin >> contact;
ifstream fin;
fin.open("studentinfo.txt");
ofstream fout;
fout.open("output.txt");
if (fin.is_open())
{
while (!fin.eof())
{
fin.getline(names, 19, ',');
fin >> age;
fin.ignore();
fin >> contact;
fin.ignore();
fout << endl;
fout << names << ',' << age << ',' << contact;
}
fin.close();
fout.close();
}
else
{
cout << "File not found " << endl;
return 0;
}
fout.open("studentinfo.txt");
fin.open("output.txt");
if (fin.is_open())
{
while (!fin.eof())
{
fin.getline(names, 19, ',');
fin >> age;
fin.ignore();
fin >> contact;
fin.ignore();
fout << names << ',' << age << ',' << contact << endl;
}
fin.close();
fout.close();
}
else
{
cout << "File not found " << endl;
return 0;
}
}
P.S I haven't read vectors or string variable yet