2016-07-14 44 views
0

我目前正试图分裂是从一个文本文件读取指定字符数组的字符串。现在我遇到了分隔符的问题,我不知道我是否可以有多个分隔符。我想要分隔的是逗号和空格。这是我的代码到目前为止。分割使用多个分隔符用C

#include <stdio.h> 
FILE * fPointer; 
fPointer = fopen("file name", "r"); 
char singleLine[1500]; 
char delimit[] = 
int i = 0; 
int j = 0; 
int k = 0; 


while(!feof(fPointer)){ 
    //the i counter is for the first line in the text file which I want to skip 

    while ((fgets(singleLine, 1500, fPointer) != NULL) && !(i == 0)){ 
     //delimit in this loop 
     puts(singleLine); 

    } 
    i++; 
} 

fclose(fPointer); 

return 0; 
} 

我已经发现迄今是使用文本字符串,对标签和这种速记例如划定办法

char Delimit[] = " /n/t/f/s"; 

那么我会在的strtok()方法使用该字符串的分隔符参数

下,但这不会让我有一个逗号作为分隔符。

并在此整点是这样我就可以开始了分隔字符串分配到变量。

样品输入:P1,2,3,2

任何帮助或参考表示赞赏谢谢。

+0

'strtok'?你能包含一个来自文本文件的示例行吗? '你发现到目前为止'的方式是什么? – thelaws

+0

@thelaws我加了一些详细信息,如果您需要澄清让我知道。 – Thorx99

+1

您可以在'strtok'中使用','作为分隔符。这里有这样一个例子:所以我只需添加一个逗号分隔符阵列http://www.cplusplus.com/reference/cstring/strtok/ – thelaws

回答

1

可以使用,作为strtok方法的分隔符。

我也认为你的意思是使用\n\t换行和制表符(我不知道/f/s是什么意思)。

尝试使用这样的:

char Delimit[] = " ,\n\t"; 

// <snip> 

char * token = strtok (singleLine, Delimit); 
while (token != NULL) 
{ 
    // use the token here 
    printf ("%s\n",token); 

    // get the next token from singleLine 
    token = strtok (NULL, Delimit); 
} 

这将改变你的样品输入P1,2, 3 , 2到:

P1 
2 
3 
2 
+0

“strtok()”方法的问题是相邻分隔符序列的潜在错误解释:“P1 ,,, 2,3,2”会产生相同的输出,空值不能使用“strtok”进行分析。 – chqrlie