使用函数标记字符串输入

问题描述

我是 C 的初学者,我在这里有这段代码,我试图标记一个“字符串”输入。我认为答案很明显,但我正在寻求帮助,因为我已经多次查看手册并且根本找不到错误标记化的目的是创建单独的进程来执行基本的 linux 命令,因为我正在尝试构建一个 shell。提前谢谢大家。

//PROMPT is defined as "$"
void tokenizeInput(char input[]) {
    char *piece;
    int i = 0;
    int *argument;
    int pst[] = 0;
    char temp = ' ';
    piece = &temp;
    
    piece = strtok(input,PROMPT);
    while (input != NULL) {
        (*argument)[pst] = piece;
        strcat((*argument)[pst++],"\0");
        piece = strtok(NULL,PROMPT);             
        puts(piece);      
        piece = NULL;  
    } 
}

我得到的错误expression must be a modifiable lvalue,位于 [pst++],它是 strcat 中的一个参数。

解决方法

从您问题的标题来看,我相信您希望获得一些有关使用 strok 的提示。下面是一个注释示例(见下文)

但是,您的代码还有一些其他问题。函数 strtok 修改参数,因此您最好将它传递给 char* 而不是 char[]。同样 pst[] 是一个数组,而 pst 本身是一个常量指针(指向分配数组的第一个内存块)。您不能增加 pst。我想你需要一个内部索引。或者,也许,根据您的想法,您想要增加 pst[0]

不要犹豫,问更多。

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

int main (int argc,char **argv)
{
  char buffer[1024],*p;

  /* This is an example of a line we ant to parse. */
  strcpy (buffer,"Hello Token World");

  printf ("Buffer is: %s\n",buffer);

  /* The function strtok process the string in 'buffer' and finds the first 
     ocurrency of any of the characters present in the string 'delimiters'
     
     p = strtok (char *buffer,char *deliminters)

     The function puts a string-end mark ('\0') where it found the delimiter
     and returns a pointer to the bining of the buffer.
*/

  /* Finds the first white space in buffer. */
  p = strtok (buffer," ");

  /* Now,go on searching for the next delimiters. 

     p = strtok (NULL,char *delimiters)

     The function "remembers" the place where it found the delimiter.
     If the furst argument is NULL,the function starts searching
     from this position instead of the start of buffer. Therefore
     it will find the first delimiter starting from where it ended
     the last time,and will return a pointer to the first 
     non-delimiter after this point (that it,the next token).
*/

  while (p != NULL)
    {
      printf ("Token: %s\n",p);
      p = strtok (NULL," ");   /* Find the next token. */
    }

  /* Notice that strtok destroys 'buffer' by adding '\0' to every
     ocurrency of a delimiter.*/

  printf ("Now buffer is: %s\n",buffer);

  /* See 'man strtok' or the libc manual for furter information. */

  return EXIT_SUCCESS;
}