TylarBen
TylarBen

Reputation: 811

Splitting input lines at a comma

I am reading the contents of a file into a 2D array. The file is of the type:

FirstName,Surname
FirstName,Surname

etc. This is a homework exercise, and we can assume that everyone has a first name and a surname.

How would I go about splitting the line using the comma so that in a 2D array it would look like this:

char name[100][2];

with

       Column1     Column2
Row 0  FirstName   Surname
Row 1  FirstName   Surname

I am really struggling with this and couldn't find any help that I could understand.

Upvotes: 0

Views: 177

Answers (1)

AusCBloke
AusCBloke

Reputation: 18502

You can use strtok to tokenize your string based on a delimiter, and then strcpy the pointer to the token returned into your name array.

Alternatively, you could use strchr to find the location of the comma, and then use memcpy to copy the parts of the string before and after this point into your name array. This way will also preserve your initial string and not mangle it the way strtok would. It'll also be more thread-safe than using strtok.

Note: a thread-safe alternative to strtok is strtok_r, however that's declared as part of the POSIX standard. If that function's not available to you there may be a similar one defined for your environment.

EDIT: Another way is by using sscanf, however you won't be able to use the %s format specifier for the first string, you'd instead have to use a specifier with a set of characters to not match against (','). Since it's homework (and really simply) I'll let you figure that out.

EDIT2: Also, your array should be char name[2][100] for an array of two strings, each of 100 chars in size. Otherwise, with the way you have it, you'll have an array of 100 strings, each of 2 chars in size.

Upvotes: 5

Related Questions