gpt4 book ai didi

c - 使用 strncopy 显示输出

转载 作者:太空宇宙 更新时间:2023-11-04 08:41:53 24 4
gpt4 key购买 nike

我从 C 开始,我必须编写一个方法来返回由空格分隔的句子中的每个单词。

到目前为止我有这个:

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

#define SIZE 100

int nextToken(char const * str, int* from, int* len);

int main(){
char str[SIZE+1];
char mot[SIZE+1];

if(fgets(str, SIZE, stdin) == NULL){
puts("Error");
return -1;
}
str[SIZE] = '\0';

int from = 0;
int len = 0;

while(nextToken(str, &from, &len)){
strncpy(mot, &(str[from]), len);
mot[SIZE] = '\0';
printf("'%s'\n", mot);
return 0;
}
return 0;
}

int nextToken(char const * str, int* from, int* len){
*from = 1;
*len = 2;
return 1;
}

我暂时知道 return 0 但它只是运行一次。

所以在 nextToken 函数中,当将 len 指向的值更改为 1 时,我得到了输入 hello 的预期输出,即 'e'

但是当将 len 指向的值更改为 2 时,我期望得到 'el' 但我得到了 'el¿■('.

为什么我有这个输出,为什么它不打印'el'

抱歉,如果它很愚蠢,但我不知道为什么会这样。我正在用 C89 编译。

最佳答案

strncpy 不会复制空终止符,以防它复制 len 个字符。在这种情况下,您需要确保该字符串明确以 null 结尾。

坦率地说,我不认为 strncpy 真的适合您在这里使用。

我会这样写:

memcpy(mot, str+from, len);
mot[len] = '\0';

并且您希望包括检查这不会导致缓冲区溢出。

关于c - 使用 strncopy 显示输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23246792/

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