gpt4 book ai didi

c - stange 输出,用空格分割文件中的字符串

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

计数器.txt

1 2 3
4 5 6
7 8 9

void  split_str(char line_str[10]) {

int i, j;
i=0;

char sub_str[10][20];
char *token;

token = strtok(line_str," ");

while (token != NULL) {
strcpy(sub_str[i], token);
i=i+1;
token=strtok(NULL," ");
}

for (j=0; j<=i; j++)
printf("The char is %s\n",sub_str[j]);


} //split_str

void main() {

file_ptr=fopen("counter.txt", "r");

while ( fgets ( line, sizeof line, file_ptr ) != NULL ) {
split_str(line);
}

fclose ( file_ptr );
}

结果:
字符为 1
字符为 2
字符为 3

字符是。"//双配额的空格
字符为 4
字符为 5
字符为 6

字符是。"
字符为 7
字符为 8
字符为 9
字符为。"

。是空格,本网站已修剪

有一些字符“””是我意想不到的双配额空格,那是什么?谢谢

最佳答案

你看到的是sub_str中的垃圾数据因为此代码不正确:

while (token != NULL) {
strcpy(sub_str[i], token);
i=i+1;
token=strtok(NULL," ");
}

for (j=0; j<=i; j++)
printf("%s\n",sub_str[j]);

for循环应该运行到 j < i这里。这是因为在 sub_str[i]你只有一些虚拟值,因为在 i=i+1 之后您退出while在 NULL 标记上循环。

尝试“在头脑中”模拟它或在调试器中运行以查看问题的实际情况。

关于c - stange 输出,用空格分割文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4085063/

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