Here's my working code:
#include <string.h>
#include <stdio.h>
//#define DATA_DELIM "|"
#define DATA_DELIM "|\n"
int main(void)
{
enum { LINE_LENGTH = 4096 };
char input[LINE_LENGTH];
#define MAX_CAT_TOK 4
char *token[100];
while (fgets(input, sizeof(input), stdin) != 0)
{
printf("Input: %s", input);
for (int i = 0; i < MAX_CAT_TOK; i++)
{
if (i == 0)
token[i] = strtok(input, DATA_DELIM);
else
token[i] = strtok(NULL, DATA_DELIM);
printf("%d: %s\n", i, token[i] != 0 ? token[i] : "<<NULL POINTER>>");
}
}
return 0;
}
On the given data, I get:
Input: C0001|H|Espresso Classics|The traditional espresso favourites.
0: C0001
1: H
2: Espresso Classics
3: The traditional espresso favourites.
Input: C0002|H|Espresso Espresions|Delicious blend of espresso, milk, and luscious flavours.
0: C0002
1: H
2: Espresso Espresions
3: Delicious blend of espresso, milk, and luscious flavours.
Input: C0003|H|Tea & Cocoa|Gloria Jean's uses only the finest cocoas and single garden teas. Always satisfying.
0: C0003
1: H
2: Tea & Cocoa
3: Gloria Jean's uses only the finest cocoas and single garden teas. Always satisfying.
Input: C0004|C|Iced Chocolate|Gloria Jean's version of a traditional favourite.
0: C0004
1: C
2: Iced Chocolate
3: Gloria Jean's version of a traditional favourite.
Input: C0005|C|Mocha Chillers|An icy blend of chocolate, coffee, milk and delicious mix-ins.
0: C0005
1: C
2: Mocha Chillers
3: An icy blend of chocolate, coffee, milk and delicious mix-ins.
Input: C0006|C|Espresso Chillers|A creamy blend of fresh espresso, chocolate, milk, ice, and flavours.
0: C0006
1: C
2: Espresso Chillers
3: A creamy blend of fresh espresso, chocolate, milk, ice, and flavours.
Input: C0007|C|On Ice|Cool refreshing Gloria Jean's creations over ice.
0: C0007
1: C
2: On Ice
3: Cool refreshing Gloria Jean's creations over ice.
With the single-character delimiter string, I get an extra newline after each of the lines numbered 3.
This looks plausibly like what you wanted. So, either there's a problem with your input (did you echo it as you read it), or you've managed to find a flaky implementation of strtok()
, or perhaps you are on Windows and the data lines have carriage returns as well as newlines, and you are seeing misleading output because of stray carriage returns.
Of these, I suspect the last (Windows and stray carriage returns) is the most likely - though I was not able to reproduce the problem even with a DOS-formatted data file (testing on MacOS X 10.6.7 with GCC 4.6.0).