c - 无法从 c 中的给定格式拆分输入字符串?

标签 c strtok

我试图通过使用 strtok()功能。为此,我在下面编写了程序,但它一直读到第一个逗号 , 定界符(注意:输入大小可能会有所不同。就像在给定的示例中,逗号在 4 位数字之后,但它可以在 k(5,6, 7, etc) 基于给定测试用例的数字)。

 fgets(str,80,stdin);

 /* read str with comma(,)delimiter  */
 token = strtok(str, ","); 

 /* walk through other tokens */
  while( token != NULL ) 
   {

       // read token string with space delimiter 
       token2 = strtok(token, " ");
       while( token2 != NULL ) 
       {
            printf("%s \n", token2);    
            token2 = strtok(NULL, " ");
       }

      token = strtok(NULL, ",");
   }

最佳答案

strtok 不可重入——您一次只能标记一个字符串。如果您想一次同时标记多个字符串,请改用 strtok_r。更好的是,始终优先使用 strtok_r 而不是 strtok,因为它的能力永远不会降低:

char *inner, *outer;
fgets(str,80,stdin);

/* read str with comma(,)delimiter  */   
token = strtok_r(str, ",", &outer);

/* walk through other tokens */
while( token != NULL ) 
{

    // read token string with space delimiter 
    token2 = strtok_r(token, " ", &inner);
    while( token2 != NULL ) 
    {
        printf("%s \n", token2);    
        token2 = strtok_r(NULL, " ", &inner);
    }

    token = strtok_r(NULL, ",", &outer);
}

您可能还想调查 strsep

关于c - 无法从 c 中的给定格式拆分输入字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36630429/

相关文章:

c - 从 TCP 数据包负载中获取主机字段

c - open命令适合二进制文件操作吗

c++ - 为什么这个IO操作会无限循环呢?

c - strtok 不会接受 : char *str

c - 将大写字母从 char 数组分离到新数组中,并在 C 中为其重新分配内存

iphone - 通过C与iDevice通信?

更改结构字符串

c - 带空格分隔符的 strtok() 函数

c - 数组值不更新

c - 在 C 中重建索引