I want to retrieve all the data inside the text file, so I will read to vector 1st then display all the data out. The 1st data in the text file I can get it properly, but the 2nd data in the text file, the username can't be retrieve and it gone.
Here's the text file data...
1|admin|admin|admin|Male|123|123|123|
1|jeff|jeff|jeff|Male|123|123|123|
And after I display all the data out...it become like this
1 admin admin admin Male 123 123 123
1 jeff jeff Male 123 123 123
Can anyone help me to solve?? THANKS
void Admin::displayMemberInfo(vector <Member> &memberProfile)
{
if(loginSucceed == true)
{
int memberID, age;
string username, password, name, gender, contact, ic;
memberProfile.erase(memberProfile.begin(),memberProfile.end());
ifstream inMember("Member.txt");
while(!(inMember.eof()))
{
string name,gender,contact, ic, username, password;
int age,memberID;
string readID,readAge;
getline(inMember,readID,'|');
istringstream(readID)>>memberID;
getline(inMember,username,'|');
getline(inMember,password,'|');
getline(inMember,name,'|');
getline(inMember,gender,'|');
getline(inMember,readAge,'|');
istringstream(readAge)>>age;
getline(inMember,contact,'|');
getline(inMember,ic,'|');
inMember.ignore(numeric_limits<streamsize>::max(), '|');
//if(username != "")
//{
// Member member(memberID, username, password, name, gender,age, contact, ic);
// memberProfile.push_back(member);
//}
cout<<memberID<<username<<password<<name<<gender<<age<<contact<<ic<<endl;
}
inMember.close();
system("pause");
}
}
You need to change this line
inMember.ignore(numeric_limits<streamsize>::max(), '|');
to
inMember.ignore(numeric_limits<streamsize>::max(), '\n');
Oh yeah, I forgot, you redeclare variables.
Try this entire function and tell me if it works better:
void Admin::displayMemberInfo(/* vector <Member> &memberProfile */) {
int memberID, age;
string username, password, name, gender, contact, ic;
//memberProfile.erase(memberProfile.begin(),memberProfile.end());
ifstream inMember("Members.txt");
if(inMember.fail()) return;
while(!(inMember.eof())) {
string readID,readAge;
getline(inMember,readID,'|');
istringstream(readID)>>memberID;
getline(inMember,username,'|');
getline(inMember,password,'|');
getline(inMember,name,'|');
getline(inMember,gender,'|');
getline(inMember,readAge,'|');
istringstream(readAge)>>age;
getline(inMember,contact,'|');
getline(inMember,ic,'|');
inMember.ignore(numeric_limits<streamsize>::max(), '\n');
//if(username != "")
//{
// Member member(memberID, username, password, name, gender,age, contact, ic);
// memberProfile.push_back(member);
//}
cout<<memberID<<username<<password<<name<<gender<<age<<contact<<ic<<endl;
}
inMember.close();
system("pause");
}
You were also re-declaring variables in the function as well as the while loop.
I commented out the vector stuff for my test.
My input file is
1|admin|admin|admin|Male|123|123|123|
2|jeff|jeff|jeff|Male|123|123|123|
Terminated with a new line. The output is
1adminadminadminMale123123123
2jeffjeffjeffMale123123123
Related
i want to create login system in c++, and i've got simple login function:
bool DBProperties::loginToSystem(string identifier, string password)
{
connectToDatabase();
prep_stmt = con->prepareStatement("SELECT * FROM user WHERE identifier_code = ? AND password = ?");
prep_stmt->setString(1, identifier);
prep_stmt->setString(2, generateHashPassword(password));
res = prep_stmt->executeQuery();
if (res->rowsCount() == 1) {
res->next();
}
delete prep_stmt;
delete con;
return false;
}
And my question is, how to store user that i get from database? Can i create object which will be visible from whole project? I need to do operates on this user from other functions.
Thanks.
If what you want is one user class that could have members like
user.name; user.password; user.email;
you could use a singleton pattern which would be declared globally.
this is a general outline of a singleton this website has a full explanation though. singletons.
``
// rough singleton pattern
class user
{
private:
user(){
// single instance checking code here
}
public:
string user;
string password;
string email;
};
user* userObject = new user();
int main(){
cout << userObject.user << endl;
cout << userObject.email << endl;
}
``
singleton patterns have a major flaw though, they are inherently difficult to expand on, say you at some point wanted to cache another user you would have to create another user class.
you could put the class on the heap(so it won't be deleted when the function ends) and then pass a pointer to your user object to wherever it's needed
the pointer method might be a better solution
// something like this
class user{
user(string user, string password, string email){
user = user;
email = email;
password = password;
}
string user;
string password;
string email;
};
int myLoginFunction(string username, string password, string email, user* userObject){
userObject = new user(username, password, email);
}
you can then use that pointer to your user object to access that object with userObjectPointer->memberValue
I am saving all the trades done by my EA into a CSV file. When a Trade is closed by the EA, I have to add string "Book Profit" to the end of particular line from the file.
eg:
Below is the line that is saved in the file while trade is open
"Buy GBPJPY 146.28 145.15", I would like to add string "Book Profit" to the end of the above line and save it to the file.
After saving the line should look like
"Buy GBPJPY 146.28 145.15 Book Profit"
int file_handle_dtf=FileOpen("MyTrades.CSV",FILE_READ|FILE_WRITE|FILE_CSV);
if(file_handle_dtf!=INVALID_HANDLE){
while(!FileIsEnding(file_handle_dtf)){
str_size1=FileReadInteger(file_handle_dtf,INT_VALUE);
//--- read the string
str1=FileReadString(file_handle_dtf,str_size1);
strBP=StringConcatenate(str1,",Book Profit");
FileWriteString(file_handle_dtf,strBP+"\n");
}
}
This code just overwrites the file and it is not readable
Seek the end of the file first before writing to it:
if (FileSeek(file_handle_dtf, 0, SEEK_END))
{
// put file writing code here
}
Use the following function with your four parameters (Buy, GBPJPY, 146.28, 145.15):
void func_replaceStringInCSV(string _order,string _symbol,string _SL,string _TP)
{
int handle=FileOpen("MyTrades.CSV",FILE_READ|FILE_WRITE|FILE_CSV);
if(handle!=INVALID_HANDLE)
{
while(!FileIsEnding(handle))
{
int lineStart=(int)FileTell(handle);
string order=FileReadString( handle);
if(FileIsLineEnding(handle))continue;
string symbol=FileReadString(handle);
if(FileIsLineEnding(handle))continue;
string SL=FileReadString(handle);
if(FileIsLineEnding(handle))continue;
string TP=FileReadString(handle);
if(FileIsLineEnding(handle))
{
if(StringConcatenate(order,symbol,SL,TP)==
StringConcatenate(_order,_symbol,_SL,_TP))
{
string blankSpace="";
int lineLen=StringLen(StringConcatenate(order,symbol,SL,TP))+3;
FileSeek(handle,lineStart,SEEK_SET);
for(int l=0;l<=lineLen;l++)
blankSpace+=" ";
FileWrite(handle,order,symbol,SL,TP,"Book Profit");
FileFlush(handle);
}
}
}
}
}
To begin with C++, I prepare a user registration and log-in program.The program I write records the information into the file.But when I open the program again, it wipes out the old record and re-writes it back.
I tried to define string and get input from text but it failed.
using namespace std;
void saveuser() {
string datausername = "test";//User name to save or read from txt
string datapassword = "pass";//password to save or read from txt
string datarealname = "realname";//Real name of the user
ofstream database;
database.open ("userdatabase.txt");
database << datausername.c_str();
database << " , ";
database << datapassword.c_str();
database << " , ";
database << datarealname.c_str();
database.close();
}
I want to store all users information on separate lines.
Like, User1's details : User1 , Pass1 , UserName1
and in other line User2 , Pass2 , UserName2
Sounds like you would like to append to the file.
To append to a file, pass the mode argument of std::ofstream::app into the open function.
Example:
void saveuser() {
....
ofstream database;
database.open ("userdatabase.txt", std::ofstream::out, | std::ofstream::app);
...
}
This will not overwrite the previous contents of the file.
I am trying to read from a csv file and add each row to a database in c++. The csv file is in the form id,firstname,surname,job my code is:
while (file.good())
{
getline (file, id, ',');
getline (file, firstname, ',');
getline (file, surname, ',');
getline (file, job, ' ');
cur->set_sql( "INSERT INTO staff VALUES (?, ?, ?, ?);" );
cur->prepare();
cur->bind(1, id);
cur->bind(2, firstname);
cur->bind(3, surname);
cur->bind(4, job);
cur->step();
cur->reset();
}
but when I run the code it returns the error Sqlite error: Could not reset the virtual machine. I do not understand what this means or how to solve it. I searched the error on google but I can't find anything about it
Error comes from libsqlite.hpp (check search on github.com)
void reset(){
int rc = sqlite3_reset(this->_s);
if (rc != SQLITE_OK) {
exception e("Could not reset the virtual machine.");
throw e;
}
this->_valid = true;
this->_has_row = false;
this->_prepared = false;
}
I haven't digg into this but it looks like sqilte query contain error or can't run.
I found out how to solve this error. I realised I was programming on a virtual machine and all I needed to do was restart it. There was nothing wrong with my code!
The following is my constructor for a Student object. I will be using a list of student. I need to store the list so even if the program is turned off, I can still access all the contents. The only way I could think of was to use reader/writer and a text file.
1) Is there a more efficient way to store this information?
2) If not, how can I use reader/writer to store each field?
public Student(String firstName, String lastName, String gender, String
state, String school, String lit, String wakeUp, String sleep, String
social,String contactInfo, String country, String major) {
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.state = state;
this.school = school;
this.lit = lit;
this.wakeUp = wakeUp;
this.sleep = sleep;
this.social = social;
this.contactInfo = contactInfo;
this.country = country;
this.major = major;
}
The possibilities are really project specific and subjective.
Some possibilities include:
CSV file which makes it easy for exporting to other programs and parsing data
Online server which allows access from any computer that has the
program and an internet connection
Text file which works for local devices that won't require many
additions
It really just depends on how you want to implement it and what method suits your needs best.
To use reader/writer to store your fields, you could use the accessor methods of each variable to store them line by line in your text file. Below is some sample code to get you started on writing to the file:
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(new FileOutputStream(FILE_LOCATION));
}
catch (FileNotFoundException ex) {
JOptionPane optionPane = new JOptionPane("Unable to write to file\n " + FILE_LOCATION, JOptionPane.ERROR_MESSAGE);
JDialog dialog = optionPane.createDialog("Error!");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
System.exit(0);
}
Iterator<YOUR_OBJECT> i = this.List.iterator();
YOUR_OBJECT temp = null;
while (i.hasNext()) {
temp = i.next();
if (temp instanceof YOUR_OBJECT) {
outputStream.println(temp.getAttribute());
}
}
outputStream.close();