这是我的工作代码:
#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;
}
根据给定的数据,我得到:
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.
使用单字符分隔符字符串,我在编号为 3 的每一行之后得到一个额外的换行符。
这看起来很像你想要的。所以,要么您的输入有问题(您在阅读时是否回显了它),或者您已经设法找到了 的易碎实现strtok()
,或者您在 Windows 上并且数据行有回车符和换行符,由于杂散的回车,您会看到误导性的输出。
其中,我怀疑最后一个(Windows 和杂散回车)是最有可能的 - 尽管即使使用 DOS 格式的数据文件我也无法重现该问题(在 MacOS X 10.6.7 上使用 GCC 4.6.0 进行测试) .