Ask coding questions

← Back to all posts
C++ - How to make this function thingy not append?
CarlosRosiles (179)

How do you make this function thingy not append? If you try it on my repl, it will append, and I don't want that. I want it to update the file. And you have to enter a character, then press enter. To make the repl work. The username is user and password is pass. (For me. I dont know if its the same thing for you)
Here is the function thingy:

ofstream caloriesburnt;
caloriesburnt.open("calories", ios_base::app);
//The on on top of this comment
Commentshotnewtop
Highwayman (1341)

You have to get rid of ios_base::app to make if not append.

CarlosRosiles (179)

@Highwayman Ok, but for some reason its deleting all the stuff in the file. Is there a way to stop this?

Highwayman (1341)

@CarlosRosiles ok, here show me an example of the before and after of your file that you want and I will tell you what you need, cause it seems like your have an xy problem rn, ok?

CarlosRosiles (179)

@Highwayman What do you mean before and after?

Highwayman (1341)

@CarlosRosiles like

before program ran:

text1 text1

after running:

text1 text1 text2 text2
CarlosRosiles (179)

@Highwayman Lets say the number in the "calories" file is

1.42

and after I run the program

0

It just clears all the data in the file. :(

Highwayman (1341)

@CarlosRosiles ok, so what do you want to do instead? do you want it to go

1.42

=>

1.42
0

like that?

CarlosRosiles (179)

@Highwayman I want it to update. Like

1.42

to

2.84

But instead, it does

1.42

to

0

and I want it to update, not to erase the data and start over. Or not to append.

Highwayman (1341)

@CarlosRosiles so you add to the number in the file instead of replacing it or just appending a second number after it?

Highwayman (1341)

@CarlosRosiles ok, then do something like

double orig;
inCals >> orig;
outCals << orig + new_num;
CarlosRosiles (179)

@Highwayman Ok but what do the variables inCals and Outcals represent?

Highwayman (1341)

@CarlosRosiles

std::ifstream inCals("calories");
std::ofstream outCals("calories");
CarlosRosiles (179)

@Highwayman It wont work. It just stays the same. But thats enough help for one day. Can we continue tommorow?

Highwayman (1341)

@CarlosRosiles ok, just ping me tmrw so I remember :)