Text file using filehandling


For Example
i have made a text file included some students data.
Now i want to change just a single student data. That file should remain same just that student's data replace.
Any logic...
yup, open an ifstream, read the file, change what you want to change, open an ofstream, write it back out. At least that's the method I know...
But when we use this method whole text file will change with new data #bugbyte
But i want to change the data of specific student while other students's data must remain same.
Hope so Now you got my point.
Indeed I got your point. Maybe if you would show some code, we could tell you why it doesn't work the way you want to. #beingProactive
here is a mini example (I will stop doing these soon):

data.txt:

Foo 9
Bar 0
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
// format: <name> <number>
// increment number if name is "Bar"
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

int main()
{
    using namespace std;
    const string filename = "data.txt";
    ifstream file(filename);
    if (!file) {
        cout << "Could not open file '" << filename << "'\n";
        return 1;
    }

    vector<string> content;
    string name;
    int num;
    while (file >> name >> num) {
        if (name == "Bar") ++num;
        content.push_back(name + ' ' + to_string(num));
    }

    ofstream out(filename);
    for (const auto& line : content)
        out << line << '\n';
    return 0;
}
Last edited on
Topic archived. No new replies allowed.