gpt4 book ai didi

c - strtok 中的可变长度

转载 作者:太空宇宙 更新时间:2023-11-04 02:59:19 25 4
gpt4 key购买 nike

我看过一些示例并尝试做一些事情,但现在我被卡住了。

工作代码是

    char quality[5][10];
char * qualities;
qualities = strtok (message, "\n");
int k = 0;
while (qualities != NULL){
if (k == 0) {
strcpy(quality[0], qualities);
}
else if ( k == 1) {
strcpy(quality[1], qualities);
}
else if ( k == 2) {
strcpy(quality[2], qualities);
}
else if ( k == 3) {
strcpy(quality[3], qualities);
}
else if ( k == 4) {
strcpy(quality[4], qualities);
}
qualities = strtok (NULL, "\n");
k++;
}

然而,这适用于固定长度(在本例中仅为 5),但是我想将一个变量分配给质量变量,但在那种情况下 while 循环将不起作用。我该怎么办?

最佳答案

替换这个 block

if (k == 0) {
strcpy(quality[0], qualities);
} else if ( k == 1) {
strcpy(quality[1], qualities);
} else if ( k == 2) {
strcpy(quality[2], qualities);
} else if ( k == 3) {
strcpy(quality[3], qualities);
} else if ( k == 4) {
strcpy(quality[4], qualities);
}
qualities = strtok (NULL, "\n");
k++;

用这两行:

strcpy(quality[k++], qualities);
qualities = strtok (NULL, "\n");

这是等效的代码,但它适用于任意数量的项目,最多为 quality 数组中的元素数量。

既然元素的数量是固定的,你应该改变

while (qualities != NULL)

while (k < N && qualities != NULL)

其中 Nqualities 中元素的数量。

关于c - strtok 中的可变长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13794720/

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