Hey there. I am not sure if can exactly explain my issue but I'll do my best. Feel free to ask me stuff if you don't understand exactly what I'm saying (typing)
Basically I am making a console application that allows you to create an account, and then to add notes to your accounts. All accounts and notes are saved in a Linear-linked list (and also onto .txt files for when the user closes the program)
My problem occurs with my log In function. In this function, I ask the user for a name (that I store in a char *). Then I look through my liner linked list of accounts and check to see if it matches any of the usernames that are in the program.
I have an account class that contains a field like this : char * username;
My problem is, that if do something like call
head -> username; (head is a pointer to a userAccount object)
head -> username gives me some weird symbol(s) instead of the proper name.
But if I declare my username as a string in my account class ( string username). IT works properly.
Note: I am calling username from another function of the same class, and I am passing head to it.
Note2: username is a public member of my account class.
If anyone has any idea what might be causing this behaviour I would be very thankful.
Please post a code example demonstrating the problem (you don't need to post the entire program). It's likely a way you are handling the pointer that is causing you to observe this behavior, but without seeing the code we can only guess.
My guess is that when using a char* you are assuming there is valid data there and memory that you can access when you really need to manually manage it yourself. The std::string class manages all that for you so it "just works", which is probably why you don't see a problem using it.
Where do those values come from? You are just passing pointers around, so the original data those things point to must be allocated somewhere (if not, that is the problem right there).
There is a menu class that calls some menu functions and the user inputs the data.
They are then stored in both a liner-linked list and also written to a file externally :)
Can you show the code that starts with reading the text input and how it eventually gets to createAccount()? I think there is probably an issue allocating the memory at some point along the way.
To be honest, though, if you can I would just use an std::string. As you've noticed, it handles all the memory allocation and such itself and prevents you from having to deal with pointers and memory management.
Well, char type represents ONE symbol and if you need to store username (which is more than 1 symbol), you need to write it to an array of char, a.k.a. string.
Hope this will help.
TC is using a C-style string; that is, a pointer to an array of characters, so it is certainly possible to do it the way they are trying to. An std::string would be much simpler, though, as I've noted.