我正在尝试使用带有制表符的strtok分隔一行。我的代码和输入如下。我想将这些令牌存储到field1、field2、field3中。
代码:
while(fgets(line,80,fp1)!=NULL) //Reading each line from file to calculate the file size.
{
field1=strtok(line," ");
//field1=strtok(NULL,"");
field2=strtok(NULL," ");
field3=strtok(NULL," ");
if(flag != 0)
printf("%s",field1);
flag++;
}
输入:
315 316 0.013
315 317 0.022
316 317 0.028
316 318 0.113
316 319 0.133
318 319 0.051
320 324 0.054
321 322 0.054
我的当前输出:(如果我打印字段1)
315 316 0.013
315 317 0.022
316 317 0.028
316 318 0.113
316 319 0.133
318 319 0.051
320 324 0.054
321 322 0.054
while(fgets(line,80,fp1)!=NULL) //Reading each line from file to calculate the file size.
{
char *p;
p = strtok(line, 't');
int itr = 0;
while(p != NULL) {
if(itr == 0){
strcpy(field1, p);
itr++;
}
else if(itr == 1){
strcpy(field2, p);
itr++;
}
else {
strcpy(field3, p);
itr = 0;
}
p = strtok(NULL, 't');
}
printf("%s%s%s", field1, field2, field3);
// store it in array if needed
}
我建议使用sscanf。它将选项卡作为分隔符进行处理。
#include <stdio.h>
#include <stdlib.h>
int
main()
{
char line[80], field1[32], field2[32], field3[32];
FILE *fp;
fp = fopen("testfile", "r");
if (fp == NULL) {
printf("Could not open testfilen");
exit(0);
}
while (fgets(line, sizeof(line), fp) != NULL) {
sscanf(line, "%s%s%s", field1, field2, field3);
printf("%s %s %sn", field1, field2, field3);
}
exit(0);
}
查看此处的信息:
http://www.cplusplus.com/reference/cstring/strtok/
您指定了空格作为分隔符以用作标记符,但您的字符串没有空格(对我来说,它看起来像制表符)。所以,strtok所做的就是从一开始就查找tab("\t")。它一直到字符串的末尾,没有找到它,但它确实找到了位于末尾的\0,所以它在开始时返回字符串,因为strtok总是在要找到的令牌之前给出字符串。
将分隔符更改为"\t",然后打印每个字段变量。