BreakingExpress

Parsing information with strtok in C

Some packages can simply course of a complete file without delay, and different packages want to look at the file line-by-line. In the latter case, you doubtless have to parse information in every line. Fortunately, the C programming language has an ordinary C library operate to just do that.

The strtok operate breaks up a line of knowledge in keeping with “delimiters” that divide every subject. It offers a streamlined strategy to parse information from an enter string.

Reading the primary token

Suppose your program must learn a knowledge file, the place every line is separated into completely different fields with a semicolon. For instance, one line from the info file would possibly appear to be this:

102*103;K1.2;K0.5

In this instance, retailer that in a string variable. You might need learn this string into reminiscence utilizing any variety of strategies. Here’s the road of code:

char string[] = "102*103;K1.2;K0.5";

Once you’ve the road in a string, you need to use strtok to tug out “tokens.” Each token is a part of the string, as much as the following delimiter. The primary name to strtok seems like this:

#embody <string.h>
char *strtok(char *string, const char *delim);

The first name to strtok reads the string, provides a null (