Reputation: 55
My code is actually getting a text input from the user and then the tokenizer is separating all the words from the input by identifying spaces. It also does more but that is irrelevant to the question i have.
I can't understand why the maximum words can be up to MAX_LINE/2. I mean why does it have to be /2?
#define MAX_LINE 4096
#define MAX_WORDS MAX_LINE/2
void tokenize(char *line, char **words, int *nwords);
/* break line into words separated by whitespace, placing them in the
array words, and setting the count to nwords */
int main()
{
char line[MAX_LINE], *words[MAX_WORDS], message[MAX_LINE];
int stop=0,nwords=0;
int result, pid;
int status;
pid_t child, w;
while(1)
{
printf("OSP CLI $ ");
/* my code*/
if (NULL==fgets(line , MAX_LINE, stdin))
return 0;
printf("%s",line);
/* my code ends */
/* read a line of text here */
tokenize(line,words,&nwords);
/* --Not using this code as i found my own---
if (strcmp (words[0], "exit")==0)
return 0;
*/
if (strcmp(line,"exit") == 0)
break;
/* More to do here */
if (strcmp(words[0], "cd")==0)
{
result = chdir(words[1]);
if (result < 0)
{
printf("No such file or directory\n");
}
}
}
return 0;
}
void tokenize(char *line, char **words, int *nwords)
{
*nwords=1;
for(words[0]=strtok(line," \t\n");
(*nwords<MAX_WORDS)&&(words[*nwords]=strtok(NULL, " \t\n"));
*nwords=*nwords+1
); /* empty body */
return;
}
Upvotes: 0
Views: 573
Reputation: 46960
A line is composed of words and separator characters (spaces I suppose) with a terminating null. A line with the max possible number of words looks like
a a a a a\0
In this example, the line has 10 characters. There are 5 words. In general N characters can't hold more than N/2 words.
Upvotes: 2