0

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

scypx
  • 67
  • 7
  • It's a shame you haven't read about vectors because that's what you need. You should read your file **into a vector**. Make the changes you need to the vector, i.e. insert an new element to the vector. Then write the changed vector out to the file. Maybe this is a good time to read about vectors? You really also need to learn how to use structs, and of course knowing strings would make this easier too. These things vectors, strings, structs aren't difficult, they make programming **easier**. Of course you have to learn them first but once learned things get easier. – john Apr 08 '20 at 07:58
  • @john oh believe me if I wasn't restricted by my instructor to do it without vectors, I would have totally liked to read about them and try out to solve this but here we are... – scypx Apr 08 '20 at 08:01
  • So what are you allowed to use? Arrays, structs, classes? What exactly. – john Apr 08 '20 at 08:02
  • I can use character arrays but i haven't reached structs and classes yet – scypx Apr 08 '20 at 08:06
  • Thats what I want to find out. Like how am I supposed to create a new line in between the data which would then place my new data at the newly created line – scypx Apr 08 '20 at 08:10
  • 2
    So I think your error is here `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.` That's not what you need to do. What you need to do is read lines from your input file and write them at the same time to your output file, until you get to the position where you need to insert the new line. Then your get the user to enter the new data. Then you output the new line. Then you carry on reading from the old data and writing to the new data. Make sense? – john Apr 08 '20 at 08:11
  • Alright this makes sense. I'll try and post the answer if I do it – scypx Apr 08 '20 at 08:13
  • FWIW, I really wouldn't use vectors for this task; it's inefficient in memory. You'd be reading the whole file into a vector, so would need enough memory for that. Then you'd be modifying the vector by inserting an entry, which would result in the entries after that having to be moved which, as the data is required to be held in a contiguous block of memory, would be quite inefficient, then writing it all out again. May be ok if you can guarantee that the file is small, but John's later suggestion to read and write a line at a time, writing the new line when required, is better. – cosimo193 Apr 08 '20 at 10:48

2 Answers2

0

Sometimes, using the Unix tools are the most elegant way, but your professor may not like the compactness of that solution. I.e. execing a Unix command directly from C++, with a nice wrapper that throws an exception if things fail.

To insert at line 8, modify for your needs:

sed -i '8i8 This is Line 8' FILE  

To actually run the sed command from C++, look at this: How do I execute a command and get the output of the command within C++ using POSIX?

Erik Alapää
  • 2,585
  • 1
  • 14
  • 25
-1

You can use the vector class :

#include <fstream>
#include <iostream>
#include <vector>
#include <string>
//some code...
std::fstream file("studentinfo.txt");
if(!file.is_open()) {
   std::cerr << "Failed to open file!" << std::endl;
   return 0;//it's better to throw an exception in c++
}
std::vector<std::string> content;
//read your file line by line
//some code
content.insert(content.begin() + pos, "some text\n");// pos is num of your line to be inserted
//some code...
file.write(content.data(), content.size());
file.close();
Gentil-N
  • 124
  • 1
  • Oh yes I know but I couldn't use vectors because my instructor hasn't taught us that yet.. cheers for helping! – scypx Apr 08 '20 at 08:45
  • Ok, so it's time to learn this. I haven't other solution for instance but "vector" is very useful and when you will know this, you will not be able to do without it. – Gentil-N Apr 08 '20 at 08:53
  • Elegant, but inefficient; for a large file you could be demanding a lot of memory and insert() results in all elements after the insertion point having to be moved. – cosimo193 Apr 08 '20 at 10:52
  • Yes, you're right but I thought that it wasn't a huge file. What is your suggestion in this case ? – Gentil-N Apr 08 '20 at 11:02