gpt4 book ai didi

C++ strtok 跳过第二个标记或连续分隔符

转载 作者:行者123 更新时间:2023-11-30 16:16:27 26 4
gpt4 key购买 nike

我正在尝试读取 CSV 逗号分隔文件,文件内容为

      one,,three

读取文件的代码是这样的......

      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

而我的期望是输出应该是这样的......

token1 = one
token2 = null
token3 = three

我确实更改了 if 语句

     if(token1 != NULL) 

     if(token1)

但它也不起作用。

检查此示例后http://www.cplusplus.com/reference/cstring/strtok/ ,我已经更新了

   token2 = strtok(NULL, ",");

   token2 = strtok(NULL, ",,");

同样不起作用

最佳答案

有一次我在读取 CSV 逗号分隔文件时遇到了这个问题。但对于分隔符连续出现的问题,我们不能使用strtok()作为解决方案。因为按照标准

The first call in the sequence searches the string pointed to by s1 for the first character that is not contained in the current separator string pointed to by s2. If no such character is found, then there are no tokens in the string pointed to by s1 and the strtok function returns a null pointer. If such a character is found, it is the start of the first token. C11 §7.24.5.8 3

因此,对于我的情况,我使用 strpbrk() 函数定义了另一个解决方案,这对您也很有用。

#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

希望这是您想要的输出。

关于C++ strtok 跳过第二个标记或连续分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56575295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com