2

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.

3 Answers 3

4

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

can you please show me a overview of the code using strtok_r? I cant find enough examples on it. I completely dont understand the difference between strtok() and strtok_r()
@user1390048 Sure, please take a look.
I dont want to read the first element (row1), if I put the line tok = strtok_r(NULL, term, &state); // subsequent invocations call with NU before printf("%s\n", tok); its printing the last element twice, how do i change the code?
@user1390048 Your change looks right. I added the line that you added right before the loop, and I got the right output. If you could post your changed code to pastebin.com, I'd take a look.
1

I believe you could use a string tokenizer with a tab delimiter. Here is an example.

Comments

1

you can use strtok

http://www.cplusplus.com/reference/clibrary/cstring/strtok/

and iterate over each word

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.