【问题标题】:Tokenizing multiple strings C标记多个字符串 C
【发布时间】:2014-03-01 18:20:27
【问题描述】:

例如,我有:

char *string = "S 27 64 Stack";
char *string2 = "R 9 3 Overflow";

如何将它们分成不同的字符串?我希望他们是这样的:

char *temp,*temp2,*temp3;
temp = S, temp2 = 27, temp3 = 64. Or:
temp = R, temp2 = 9, temp3 = 3.

我不知道用户输入的是一位数字还是一位数字。我写道:

char *input; input = malloc(100*sizeof(char));
char *temp, *temp2,*temp3;

   else if(input[0] != NULL){


      if( *(input+2) != ' ' && *(input+4) != '0'){

       temp = strtok(input, " ");
       temp2 = strtok(input+2," ");
       temp3 = strtok(input+4," ");

      }

      else if( *(input+3) != ' '){

       temp = strtok(input, " ");
       temp2 = strtok(input+2, " ");
       temp3 = strtok(input+5, " ");
      }

   }

当我尝试单独使用一位数算法或两位数算法时没有问题。但是,当我尝试将它们链接并一起使用时,我只看到 Segmentation Fault(Core dumped) 错误。

感谢任何帮助。

【问题讨论】:

  • 为什么为temps 分配内存并使用sscanf(input,"%s %s %s",&temp,&temp2,&temp3) 会出错?

标签: c arrays string tokenize


【解决方案1】:

第二次和第三次调用strtok的第一个参数应该是NULL,尝试替换

temp = strtok(input, " ");
temp2 = strtok(input+2," ");
temp3 = strtok(input+4," ");

通过

temp = strtok(input, " ");
temp2 = strtok(NULL, " ");
temp3 = strtok(NULL, " ");

那么你就不需要 if input[0], if input[2], ...

查看 strtok 文档:http://www.cplusplus.com/reference/cstring/strtok/

【讨论】:

    猜你喜欢
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多