1

I'm having a problem, I want to save all ID numbers in the text file, but it only saves the last ID number that user input.

#include <iostream> #include <fstream> #include <iomanip> #include <string> using namespace std; int main() { string line; int idnum; ofstream IdData ("data.txt"); cout<<" Enter your ID number: "<<endl; cin>>idnum; if(IdData.is_open()) { IdData<< "ID number of voter is: "; IdData << idnum << endl; IdData.close(); } else cout<<" Unable to open file"; ifstream Data ("data.txt"); if(Data.is_open()) { while (getline (Data, line)) { cout<< line << endl; } Data.close(); } else cout<<" Unable to open file"; } 
3
  • When you say the 'last' ID number, what do you mean? You are only asking for one ID number! Commented Oct 15, 2019 at 18:11
  • Yes, but in the text file I want to see all ID numbers that were typed by different users Commented Oct 15, 2019 at 18:13
  • BTW, if IdData fails to open, your program continues after printing the messsage. You may want to use return EXIT_FAILURE; after printing the message. Commented Oct 15, 2019 at 18:25

1 Answer 1

0

You are asking the user for only 1 ID, and then you are overwriting the existing file with a new file that contains that 1 ID.

std::ofstream destroys the contents of an existing file unless you explicitly request it not to do so. So, for what you are attempting to do, to append a new ID to the end of the existing file, you need to include the app or ate flag when opening the std::ofstream (see C++ Filehandling: Difference between ios::app and ios::ate?), eg:

ofstream IdData ("data.txt", ios::app); 

Or:

ofstream IdData ("data.txt", ios::ate); 
Sign up to request clarification or add additional context in comments.

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.