问题描述
我想读取CSV逗号分隔的文件,文件内容是
I am trying to read CSV comma delimited file, content of file are
one,,three
读取文件的代码是...
And code to read file is this…
inFile.getline(line, 500);
token1 = strtok(line, ",");
token2 = strtok(NULL, ",");
token3 = strtok(NULL, ",");
if(token1 != NULL){
cout << "token1 = " << token1 << "\n";
}else{
cout << "token1 = null\n" ;
}
if(token2 != NULL){
cout << "token2 = " << token2 << "\n";
}else{
cout << "token2 = null\n" ;
}
if(token3 != NULL){
cout << "token3 = " << token3 << "\n";
}else{
cout << "token3 = null\n";
}
输出为
token1 = one
token2 = three
token3 = null
我的期望是输出应该是这样的...
Whereas my expectation are that output should be like this…
token1 = one
token2 = null
token3 = three
如果
I did change if statements from
if(token1 != NULL)
$ b b
To
To
if(token1)
但它也不起作用。
查看此示例,我已更新
token2 = strtok(NULL, ",");
至
token2 = strtok(NULL, ",,");
同样不起作用
推荐答案
一旦我在读取CSV逗号分隔文件时遇到了这个问题。但是我们可以使用 strtok()
作为我们的解决方案,在这样的问题中分隔字符连续出现。因为根据标准
Once I did face this problem while reading CSV comma delimited file. But we can use strtok()
as our solution in such problem were delimited character appears consecutively. Because according to the standard
所以,对于我的case,我使用strpbrk()函数定义了另一个解决方案, 。
So, for my case I did define another solution using strpbrk() function which will also useful for you.
#include<iostream.h>
char *strtok_new(char * string, char const * delimiter){
static char *source = NULL;
char *p, *riturn = 0;
if(string != NULL) source = string;
if(source == NULL) return NULL;
if((p = strpbrk (source, delimiter)) != NULL) {
*p = 0;
riturn = source;
source = ++p;
}
return riturn;
}
int main(){
char string[] = "one,,three,";
char delimiter[] = ",";
char * p = strtok_new(string, delimiter);
while(p){
if(*p) cout << p << endl;
else cout << "No data" << endl;
p = strtok_new(NULL, delimiter);
}
system("pause");
return 0;
}
输出
one
No data
three
希望这是您想要的输出。
Hope so this is your desired output.
这篇关于c ++ strtok跳过第二个令牌或连续的分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!