1

/*我不确定我在数组中保存令牌的代码是否准确。之所以如此,是因为每当我运行我的程序时, token[0]与我的变量进行比较的代码既不会给出输出,也不会执行分配的函数。

因此,我确信我的编码有些不准确。*/

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

int main()
{
    //variable declarations        
   const char *array[] = {"ax","bo","cf"};
   char delim[]=" \n";
   char* myline;
   size_t max = 500;
   char* token1;
   char* token2[max];
   int n = 0;


   while(1)    //loop always
   {      
      printf("Enter an argument\n");   //asks for an input


      getline (&myline, &max, stdin);     //read the input/line              

      //for loop -- splits up the line into tokens
      for(token1 = strtok(myline, " "); token1 != NULL; token1 = strtok(NULL, delim))
      {                  

         token2[n] = malloc(strlen(token1)+1);     //allocate some space/memory to token2[n]

         //save the token in an array by copying from token1 to token2
         strcpy(token2[n],token1);


         int m;

         for(m = 0; m<sizeof(array);m++)    //loop through the array elements for comparison
         { 
            //compare array at index m with token at index 0 --  compare only first token with a specific variable 

           if(strcmp(token2[0], array[m]) == 0)
           {
               printf("equal");
           }
         }
       }

   free(token2[n]);     //deallocate assigned memory
   }       
 return(0);
}
4

2 回答 2

0

我认为你应该尝试像这样的字符串向量

矢量 < 字符串 > str = { "ax","bo","cf" };

于 2017-02-09T00:54:58.357 回答
0

它们似乎是您当前代码中的一些问题:

  • for(m = 0; m<strlen;m++)是不正确的。strlen()是一个<string.h>用于获取 C 字符串长度的函数。既然你想要array[i],你需要array在警卫中包括大小。要查找数组的大小,您可以使用sizeof(array)/sizeof(array[0]). 将其包含在宏中会很好:

    #define ARRAYSIZE(x) (sizeof x/sizeof x[0])
    

    那么你的循环可以是:

    size_t m;
    for(m = 0; m<ARRAYSIZE(array); m++)
    
  • 您需要检查 return of malloc(),因为它可以NULL在分配空间失败时返回。这是一种检查方法:

    token2[n] = malloc(strlen(token1)+1);
    if (token2[n] == NULL) {
        /* handle error */
    
  • 可以通过简单地使用来跳过malloc()/strcpy()步骤strdup

  • getline()返回-1读取一行失败,所以检查一下这个很好。它还\n在缓冲区的末尾添加了一个字符,因此您需要将其删除。否则,strcmp将永远找不到相等的字符串,因为您将比较strcmp("string\n", "string"). 您需要\n在缓冲区中找到该字符,并将其替换为\0空终止符。

    您可以像这样实现:

    size_t slen = strlen(myline);
    if (slen > 0 && myline[slen-1] == '\n') {
        myline[slen-1] = '\0';
    }
    
  • 您还需要free()char*.token2[]

  • 由于您使用相同的分隔符strtok(),因此最好这样做const。所以const char *delim = " \n";改为。

我在评论中建议了很多修复,所以我没有在这里发布它们,因为你似乎已经用这些建议更新了你的代码。

于 2017-02-09T01:11:52.320 回答