2017-02-26 54 views
0

我想读取用户输入,将采取作为命令和某些方法将基于输入执行。例如,输入可能是:阅读用户输入与各种参数

allocate 3 
write 3 ABC 10 
quit 

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

回答

1

使用fgets()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