I'm trying to read user input that will be taken in as commands and certain methods will be executed based on the input. For example, the input could be:
allocate 3
write 3 ABC 10
quit
Each part of the inputs are crucial parameters for their respective methods. I've been trying to figure out how to use scanf()
and fgets()
to account for the variation in input.
Use fgets() and strtok() combined and you can get down to something like this:
#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;
}
Output:
write 3 ABC 10
write
3
ABC
10