I’m a Java/PHP programmer learning C++.
I’ve created a class called UserAccount and a class called Database.
I have an input file with five names:
Bob
Sam
Jane
Mark
Ann
I have the following (pseudo)code:
UserAccount *ua;
while (reading through the list of names, line by line) {
ua = new UserAccount(name); // Create a new user based on this name
Database->add(ua); // Add the user to the database
}
Database->listAllUsers();
The output should mirror the input file. Instead, I get:
Ann
Ann
Ann
Ann
Ann
I assume this has something to do with pointers, but I can’t figure it out. I think I’ve provided enough information to identify the problem, but if the (pseudo)code above looks correct, I can provide more.
To follow up from my comments. You are likely running afoul of pointers, the
std::stringclass will give you behaviour much more similar to that of Java.The simplest solution will be to use the string
strdup()call.Alternatively you could use
std::string, but I’ll leave that to your learning process. There is a lot of information on pointers out there, it will help your learning to understand pointers intimately.Good luck.