Faster I/O in C

后端 未结 8 1941
自闭症患者
自闭症患者 2021-02-09 04:40

I have a problem which will take 1000000 lines of inputs like below from console.

0 1 23 4 5
1 3 5 2 56
12 2 3 33 5
...
...

I have used scanf,

8条回答
  •  执念已碎
    2021-02-09 05:22

    Use fgets(...) to pull in a line at a time. Note that you should check for the '\n' at the end of the line, and if there is not one, you are either at EOF, or you need to read another buffer's worth, and concatenate the two together. Lather, rinse, repeat. Don't get caught with a buffer overflow.

    THEN, you can parse each logical line in memory yourself. I like to use strspn(...) and strcspn(...) for this sort of thing, but your mileage may vary.

    Parsing: Define a delimiters string. Use strspn() to count "non data" chars that match the delimiters, and skip over them. Use strcspn() to count the "data" chars that DO NOT match the delimiters. If this count is 0, you are done (no more data in the line). Otherwise, copy out those N chars to hand to a parsing function such as atoi(...) or sscanf(...). Then, reset your pointer base to the end of this chunk and repeat the skip-delims, copy-data, convert-to-numeric process.

提交回复
热议问题