There are a few separate things here. First this, "
Also, how do you input the code like that?".
Use code tags. Type the tags yourself like this,
[code]your code here[/code]
or (recommended), simply select the code and click the
<>
formatting button to the right of the editing window.
Now the program itself.
In function
readData()
, this line,
|
string * theFields[5] = {split(lineBuffer, ',')};
|
has problems. It declares an array of pointers to strings. The first element,
theFields[0]
is assigned the address of the array returned by
split()
, the remaining four elements are initialised to zero.
Hence the code which displays the name and address details will output those values, which are pointers, so are displayed in hexadecimal as you stated above.
How to fix it? Well, instead of an array of pointers to strings, just declare a single pointer to strings, like this:
|
string * theFields = split(lineBuffer, ',');
|
That is probably the biggest problem fixed, though there remain a few remaining bugs to be cleared up after that.
Other issues
The constant
FileName
is defined but never used. Instead, the file name is coded as a literal in two separate places in the code. The advantage of using a defined constant is that it guarantees that the value will be consistent throughout, and if you ever want to change it, it need be done only once, in an easy-to-find place at the top of the code, rather than having to scroll through the entire program looking for where it needs to be changed multiple times.
Similarly, the constant
delimiter
is used in function
writeData()
but a literal ',' is used instead in function
readData()
. Again, using the constant instead of a literal ensures consistency and makes it easy to change if need be.
In main(),
ofstream MyAddress
is defined but never used. It should be deleted.
In function
menu()
the user input is converted to upper case, thus checking for both 'E' and 'e', 'A' and 'a' etc. is unnecessary.
In function
readData()
there is an extra getline() inside the body of the loop, which causes the program to skip alternate lines from the file, and only display the even-numbered ones. That function is also calling the menu() function which is unnecessary and causes unwanted behaviour. Remove that line.
In function
split()
, the array is allocated dynamically using new[] but there is no corresponding delete[] to release that memory. This causes a memory leak. You can fix it by putting
delete [] theFields;
in function
readData()
just after the cout statements but still inside the while loop, so that for each call of function split() there is a matching delete [].
One more comment. The function split() seems to work, but it might be simplified by using a stringstream and getline with the required delimiter. That would neatly break the line at each comma in just a few lines of code.