1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
#include<stdio.h>
#include<string.h>
void breakUp(char *, char *, char *, char *, int* );
int main()
{
char line[80], comm[10], p1[10], p2[10];
int len, n=0;
printf("Please Enter a command: ");
fgets(line, 80, stdin);
/* get rid of trailing newline character */
len = strlen(line) - 1;
if (line[len] == '\n')
line[len] = '\0';
/* Break up the line */
breakUp(line, comm, p1, p2, &n);
printf ("%d things on this line\n", n);
printf ("command: %s\n", comm);
printf ("parameter 1: %s\n", p1);
printf ("parameter 2: %s\n", p2);
return 0;
}
/*
This function takes a line and breaks it into words.
The orginal line is in the char array str, the first word
will go into the char array c, the second into p1, and the
the third into p2. If there are no words, the corresponding
char arrays are empty. At the end, n contains the number of
words read.
*/
void breakUp(char *str, char *c, char *p1, char *p2, int* n)
{
c[0] = p1[0] = p2[0] = '\0';
int j = 0; // str array index
int i = 0; // index of rest of the arrays
n[0] = 0;
// stores first word in array c
while(str[j]!= ' '|| str[j] == '\0')
{
c[i]= str[j];
i++;
j++;
}
// increases n count, moves j into next element
// and sets i back to index 0
if (str[j] == ' '|| str[j] == '\0')
{
c[i] = '\0';
n[0]++;
j++;
i =0;
}
// stores second word in array p1
while(str[j]!= ' '|| str[j] == '\0')
{
p1[i]= str[j];
i++;
j++;
}
// increases n count, moves j into next element
// and sets i back to index 0
if (str[j] == ' '|| str[j] == '\0')
{
p1[i] = '\0';
n[0]++;
j++;
i =0;
}
// stores 3rd word in array p2
while(str[j] != ' ' || str[j] == '\0')
{
p2[i] = str[j];
i++;
j++;
}
// increases n count, moves j into next element
// and sets i back to index 0
if(str[j] == ' ' || str[j] == '\0')
{
p2[i] = '\0';
n[0]++;
}
}
|