使用各种参数读取用户输入

Reading user input with various parameters

我正在尝试读取将作为命令接收的用户输入,并且将根据输入执行某些方法。例如,输入可以是:

allocate 3
write 3 ABC 10
quit

输入的每一部分都是各自方法的关键参数。我一直在尝试弄清楚如何使用 scanf()fgets() 来解释输入的变化。

结合使用fgets() and strtok(),你可以得到这样的结果:

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

int main(void)
{
   char mystring [100];
   char *pch;
   while( fgets (mystring , 100 , stdin) ) /* break with ^D or ^Z */
   {
       //puts (mystring);
       pch = strtok (mystring," ,.-");
        while (pch != NULL)
        {
            // do someting with pch, check if it's a command or an argument
            printf ("%s\n",pch);
            pch = strtok (NULL, " ,.-");
        }
   }
   return 0;
}

输出:

write 3 ABC 10

write
3
ABC
10