0

im trying to make a loop that asks a command from stdin and checks if it's valid or not,
and the command for example will be in this format :
Command then seperated with any amount of spaces then a Letter then comma then a double a comma and a double

example :

command A,24.3,7.8

doesnt matter how many spaces there are so it may be :

 command       A,    24.3,7.8

and thought i'd use strtok but not sure how does it work...

and to use strtok to recieve a pointer which would be the end of each word,
so the first time it runs it should detect the first space and then after that the commas
how do i do that..?
as the for loop was intended to run 2 times since there will be two commas in s:

  int i;
  char s[100]={0};
  char *comma=",";
  char *cp;
  printf("Enter a command:\n");
  gets(s);
  cp=strtok(s,comma);
  for(i=0;i<2,i++)
  cp=strtok(NULL,comma)
3
Contributors
4
Replies
27
Views
5 Months
Discussion Span
Last Post by Nutster
0

I stopped using strtok() years ago (like 25+) because it modifies the original string, adding null characters for each token found. I find other methods work better, and in some cases faster, to parse strings.

0

@rubberman then what methods do you suggest, i'd be thankful to learn one !

0

im gone through the problem, but a question:
how do i scan from s in parts?
like if i'd have this line of input:

command       A,    24.3,7.8

first scan the command, do something with it. then scan A and do somethign with, and so on.. ?

Edited by Adam_35

0

I am assuming that command A actually tells the program how to manipulate the two numbers, so you can check each command in a switch statement then if the command given is not recognised, have a default: clause to report "Unknown command".

Read each line into a buffer, making sure you have not reached the end of the input, then use sscanf to parse the string, again making sure you parsed all fields by checking the return value of sscanf. sscanf can skip any number of spaces after the first string, if you put a space between the string specifier and the character specifier.

You could try to use scanf to do the parsing, but if you have invalid input, scanf will try to pick up where it left off, say at a bad floating point number, which is not what you would want this to do. Instead report that the line is bad and read the next line.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.