how can i edit the content of a file??

Sep 9, 2012 at 8:14am
Hi guys, im new at c++ and I wonder how to edit the content of a file
here is my "text.txt" inputs

Mark
1000
Lester
200

how can i make it become
Mark
500
Lester
200
Sep 9, 2012 at 8:15am
Sep 9, 2012 at 8:16am
Yes please >.<
Last edited on Sep 9, 2012 at 8:22am
Sep 9, 2012 at 8:28am
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <fstream>

int main(void) {
	std::ofstream writeFile(arg[1]);
	writeFile << "Mark\n500\nLester\n200";
	writeFile.close();
	return 0;
}

Do you want the code to JUST modify the second line or re-write the whole file?
Sep 9, 2012 at 8:29am
I just need to edit the 2nd line. Can you also use using namespace std; Im having problem without it.
Last edited on Sep 9, 2012 at 8:30am
Sep 9, 2012 at 8:47am
What's the problem? There are quite a few reasons why you shouldn't use the whole namespace.
Sep 9, 2012 at 8:48am
i just dont get the std:: >.< having trouble but i can still figure it out.
and also the program is like for a save game file
Last edited on Sep 9, 2012 at 8:48am
Sep 9, 2012 at 9:06am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <fstream>

int main(int argc, char *arg[]) {
    std::string buf;
    std::ifstream readFile(arg[1]);
    getline(readFile, buf, '\0');
    readFile.close();
    size_t pos = buf.find_first_of('\n', 2);
    buf.replace(buf.begin()+(pos+1), buf.begin()+(pos+5), "500");
    std::ofstream writeFile(arg[1]);
    writeFile << buf;
    writeFile.close();
    return 0;
}

Just remove every instance of the std prefix and add using namespace std.
Last edited on Sep 9, 2012 at 9:07am
Sep 9, 2012 at 12:26pm
int main(int argc, char *arg[]) first time encounter.. what do it do??
Sep 9, 2012 at 12:43pm
@l3st3r
It makes it possible to send arguments to the program through the command line. argc is the number of arguments. arg is an array containing the argc arguments stored as c strings. If argc > 0 then arg[0] will contain the name that was used to invoke the program.

Example:
If you run a program named g++ from the command line as g++ -o k main.cpp then argc and arg will contain the values:
argc = 4
arg[0] = "g++"
arg[1] = "-o"
arg[2] = "k"
arg[3] = "main.cpp"
Topic archived. No new replies allowed.