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.
You can use
strtokto tokenize your string based on a delimiter, and thenstrcpythe pointer to the token returned into yournamearray.Alternatively, you could use
strchrto find the location of the comma, and then usememcpyto copy the parts of the string before and after this point into yournamearray. This way will also preserve your initial string and not mangle it the waystrtokwould. It’ll also be more thread-safe than usingstrtok.Note: a thread-safe alternative to
strtokisstrtok_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%sformat 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 100chars in size. Otherwise, with the way you have it, you’ll have an array of 100 strings, each of 2chars in size.