0

I have a text file only have one number in it.

I would like to open the file and read the number, then I would like to input a new number from console. Then add the previous number and inputted number together. For example, the numeber already in file is 5, then I enter 10, I want to write 15 the the file and loop again. My code is listed below:

#include "stdafx.h" #include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> using namespace std; int main() { string s; cout << "Please enter a new number" << endl; while (getline(cin, s)) { if (s.empty()) { break; } fstream ff; string pre; ff.open("file.txt", ios::out | ios::in); if (ff.is_open()) { // read the pre number getline(ff, pre); cout << "Pre number: " << pre << endl; // Write new number int new_number = stoi(pre) + stoi(s); ff << new_number << endl; // Read the new number ff.seekg(ios::beg); getline(ff, pre); cout << "New number: " << pre << endl; } ff.close(); } return 0; 

the problem is it cannot write the input number to the file. Always the existing the number in the file.

Please enter a new number 12 Pre number: 78 New number: 78 12 Pre number: 78 New number: 78 12 Pre number: 78 New number: 78 

Can anyone give me a hint?

2 Answers 2

1

You should use std::ostream::seekg to set ostream to point to the new location set by istream and also use std::ostream::seekp to set istream to point to the new location that ostream has set.

Sign up to request clarification or add additional context in comments.

Comments

1

You can also use std::fopen with r+,a+ flags for read/write to file.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.