Search code examples
cstringfgetswords

How to separate words by numbers from a string


I have a text file called commands.txt which contains some commands followed by some arguments. Example:

STOP 1 2 4
START 5 2 1 8
MOVE
CUT 0 9

I want to read every line from this text file and to print something like this

STOP: 1 2 3
START: 5 2 1 8
MOVE:
CUT: 0 9

I read every line with fgets and then I tried using sscanf but doesn't work.

char line[100]   // here I put the line
char command[20] // here I put the command
args[10]         // here I put the arguments



 #include<stdio.h>
    int main()
    {
    FILE *f;
char line[100];
char command[20];
int args[10];

f=fopen("commands.txt" ,"rt");
while(!feof(f))
{
fgets(line , 40 , f);
//here i need help
}
fclose(f);
return 0;
}

Can you help me?


Solution

  • take a look at this, and use whitespace characters as the delimeter.