Reputation: 141
I have a text file with 100 rows and 512 columns, each column is separated by a tab:
row1 00 00 20 00 11 00 00 00 00 10
00 11 00 55 77 00 00 70 21 00
90 ...
I would like to read through each row and store value in each column in an array.
I dont want to use sscanf
and separate the variables, as it requires creating another 500 variables.
If I use fgets
, I can get the whole line, but how do I separate columns with spaces and store them in an array?
Thanks.
Upvotes: 2
Views: 2490
Reputation: 726599
You can use strtok_r
, a reentrant version of strtok
, to separate elements of a string into tokens. You can call strtok_r
in a loop, call atoi
on each token, and add tokens to the array for the row.
strtok_r
has a usage pattern that is nearly identical to that of strtok
, but it has an extra parameter to represent the current state of the tokenizer. Regular strtok
keeps that state in the static memory, making the function non-re-entrant.
const char *term = "\t\n\r "; // word terminators
char str[] = "quick brown fox jumps over the lazy dog";
char *state; // Invocation state of strtok_r
char *tok = strtok_r(str, term, &state); // First invocation is different
while (tok) {
printf("%s\n", tok);
tok = strtok_r(NULL, term, &state); // subsequent invocations call with NULL
}
Upvotes: 4
Reputation: 4623
you can use strtok
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
and iterate over each word
Upvotes: 1
Reputation: 2028
I believe you could use a string tokenizer with a tab delimiter. Here is an example.
Upvotes: 1