【发布时间】:2017-07-17 11:19:36
【问题描述】:
我正在尝试读取将作为命令接收的用户输入,并且将根据输入执行某些方法。例如,输入可能是:
allocate 3
write 3 ABC 10
quit
输入的每个部分都是各自方法的关键参数。我一直试图弄清楚如何使用scanf() 和fgets() 来解释输入的变化。
【问题讨论】:
标签: c io user-input scanf fgets
我正在尝试读取将作为命令接收的用户输入,并且将根据输入执行某些方法。例如,输入可能是:
allocate 3
write 3 ABC 10
quit
输入的每个部分都是各自方法的关键参数。我一直试图弄清楚如何使用scanf() 和fgets() 来解释输入的变化。
【问题讨论】:
标签: c io user-input scanf fgets
结合使用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
【讨论】: