【问题标题】:Trouble splitting string into array in C在C中将字符串拆分为数组时遇到问题
【发布时间】:2014-12-05 22:28:49
【问题描述】:

我想将一个 char 字符串拆分成一个数组 temp_dow。

//parse incoming string
char input[] = {"1111111,0000000,1010101"};
char temp_dow[3][7];
char *tok1;
int i = 0;
tok1 = strtok(input, ",");
while (tok1 != NULL) {
    char temp[7];
    strcpy(temp, tok1);
    strcpy(temp_dow[i],temp);
    tok1 = strtok(NULL, ",");
    printf ("<<<<<<<< %s\n",temp_dow[i]);
    i++;
}
printf ("******* %s\n",temp_dow[0]);
printf ("******* %s\n",temp_dow[1]);
printf ("******* %s\n",temp_dow[2]);

输出不匹配。 while 循环外的 temp_dow[] 是完全错误的。它显示的是指针的值而不是实际值?

这是输出。

  <<<<<<<< 1111111
  <<<<<<<< 0000000
  <<<<<<<< 1010101
  ******* 1010101
  ******* 
  ******* 

谢谢

【问题讨论】:

  • 7 --> 8 : +1 表示 NUL 字符。
  • strcpy(temp, tok1); strcpy(temp_dow[i],temp); - 为什么?? 另外,为 NUL 终止符分配空间。
  • 确实如此。为什么不简单地 strcpy(temp_dow[i], tok1); ?删除上面的两行。
  • 啊,谢谢! Nul 终止符是问题所在。
  • 在较新的程序中使用strsep()。虽然strtok() 是可移植的,但它无法处理空字段。

标签: c arrays string split char


【解决方案1】:

strtok 文档指定:

记号的结尾自动被一个空字符替换,并且记号的开头由函数返回。

您的每个令牌都是 7 位数字,您为每个令牌分配 7 个字符。但是,这不考虑空字符终止符。您实际上需要 8 个字符的空间。

您应该将您的 temp_dow 声明更改为:

char temp_dow[3][8];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多