gpt4 book ai didi

c++ - strtok_r 导致段错误

转载 作者:搜寻专家 更新时间:2023-10-31 00:08:31 28 4
gpt4 key购买 nike

这段代码是解析一个csv文件,但是会导致segmentation fault。我可以在这里看到类似的代码:Nested strtok function problem in C

它们看起来一样,但我的代码导致段错误。为什么?

#include <cstdlib>
#include <string.h>
#include <stdio.h>
#include <vector>

using namespace std;

struct inputTuple{
int user, item, rating;
};

int main(void)
{
char xdata[] = "1,88,0,874965758;1,2,1,876893171;1,99,1,878542960;";
vector<inputTuple> input;

int maxUser = 0, maxItem = 0;
int user, item, rating;

char *end_str;
char *data_point = strtok_r(xdata, ";", &end_str);

while(data_point != NULL) {
char *end_attr;
char *data_point_attr = strtok_r(data_point, ",", &end_attr);
while(data_point_attr != NULL) {

user = atoi(data_point_attr);
data_point_attr = strtok_r(NULL, ",", &end_attr);
item = atoi(data_point_attr);
data_point_attr = strtok_r(NULL, ",", &end_attr);
rating = atoi(data_point_attr);
strtok_r(NULL, ",", &end_attr);
input.push_back({user, item, rating});
maxUser = max(maxUser, user);
maxItem = max(maxItem, item);
}
data_point = strtok_r(NULL, ";", &end_str);
}
return 0;
}

最佳答案

您的内部循环不是必需的,而且对您的程序有害。

内层循环抽取3个token,然后继续,抽取第4个token但中间到达NULLatoiNULL : 段错误。

您只需要一个循环(尽管添加了 assert 语句以保持理智):

    while(data_point != NULL) {
char *end_attr;
char *data_point_attr = strtok_r(data_point, ",", &end_attr);

user = atoi(data_point_attr);
data_point_attr = strtok_r(NULL, ",", &end_attr);
assert(data_point_attr != NULL);
item = atoi(data_point_attr);
data_point_attr = strtok_r(NULL, ",", &end_attr);
assert(data_point_attr != NULL);
rating = atoi(data_point_attr);
strtok_r(NULL, ",", &end_attr);
input.push_back({user, item, rating});
maxUser = max(maxUser, user);
maxItem = max(maxItem, item);

data_point = strtok_r(NULL, ";", &end_str);
}

更好的解决方案是使用真正的 C++ 解决方案来拆分字符串。

关于c++ - strtok_r 导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48708088/

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