Nobu
Nobu

Reputation: 11

C++ ofstream: save to a new line instead of overwriting old one

So im writing a simple program where you input 2 numbers and the product of those 2 numbers is printed out in the console, i have used ofstream to log the numbers successfully. My question is how do i make it print to another line every time the program runs, i probably dont make complete sense so here is kind of what i mean:

1st run:

Number 1: 10  Number 2: 45

2nd run:

Number 1: 10  Number 2: 45
Number 1: 50 Number 2: 13

i want it to write to a new line and not replace the first basically, any help would be greatly appreciated, i gather it is quite easy but i cant find a method.

Upvotes: 0

Views: 1562

Answers (2)

HellboyVN
HellboyVN

Reputation: 142

maybe you can try this small example for appending the next execution to the log file:

#include <fstream>      
#include<iostream>    
using namespace std;

int main () {

  std::ofstream ofs;
  int number1, number2;
  ofs.open ("test.txt", std::ofstream::out | std::ofstream::app);
  cout << "Number1: ";
  cin >> number1;
  cout << "Number2: ";
  cin >> number2;
  cout << "Sum of two numbers: " << number1 + number2;
  ofs << "Number1: " << number1 << " Number2: " << number2 << std::endl;

  ofs.close();

  return 0;
}

Upvotes: 0

James Hagborg
James Hagborg

Reputation: 165

It sounds like what you want to do is append to the file, not overwrite it. In the constructor of ofstream, or when you call open, pass std::ios_base::app as the second argument.

See https://en.cppreference.com/w/cpp/io/basic_filebuf/open

Upvotes: 4

Related Questions