Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Looking for Help for reading a string from an array

Status
Not open for further replies.

SteeleFusion

Programmer
Oct 26, 2007
2
GB
Hey,

I have been writing a simple program in C which uses fget to read in the first line of a text file into an array called lines[0].

The line of text is a name in the form "Bloggs, Joe" which is what is stored in the array.

However, I only really want to store the surname in the array. i.e. I would like the array to actually hold "Bloggs".

Is there a simple way to do this? I suppose its a bit like getWord (I've used it in other prog. languages.)

Is it a better approach the just read in the line in a different way, or is it easy enough to by manipulating the array itself?

(To give you a bigger idea of the program as a whole, I will be reading in other lines of the address and then adding it to a structure (record) which has 3 elements (surname, address, postcode).

Any help would be much appreciated.

CJ
 
strtok() sounds like it would be the easiest thing here.
Code:
strtok( lines, "," );
 
Thanks for your help so far.

I have tried te strtok command as suggested and it does indeed change the contents to just the surname, "Bloggs". However, would I need to add an EOS terminator to the end of the "Bloggs" string?

The reason I ask is in my program I am comparing the values held in a struct called mailentry, so I am comparing mailentry1->surname with mailentry2->surname. When I "hardwire" a surname into a structure to check, my program works (i.e. when I explicitly tell it mailentry->surname ="Jones".). However, after using

strtok(lines[0], ",")

and then using the assignment

mailentry->surname= lines[0];

The program is not performing as expected.

Any ideas why this is the case?
 
There is no such thing as a string assignment in C. In many cases, all you end up doing is copying pointers to strings. If the thing you're pointing at changes, then all the pointers which point to the same thing also change.

> mailentry->surname= lines[0];
You need to make sure surname is an array of characters (and not just a pointer), then do
[tt]strcpy( mailentry->surname, lines[0] );[/tt]



--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top