Reputation: 111
char inputp1[132], inputp2[132], inputp3[132], inputp4[132], inputp5[132];
char input[MAX_NAME_SZ];
printf("-> ");
fgets (input, MAX_NAME_SZ, stdin); // user input
input[strcspn(input, "\n")] = 0;
int count=0,i,len; //counting
len = strlen(input);
for(i=0;i<=len;i++)
{
if(input[i]==' ')
count++;
}
printf("the number of words are: %d\n",count + 1);
strcpy(inputp1, strtok(input , " ,-"));
for (count = count; count < 0; count-- )
{
strcpy(inputp2, strtok(NULL, " ,-"));
}
Okay so I have user input and im making it so that at every single ,- or space it will make a token.
What im wondering is is their a way to make a for statment so that for every single string after a space it will run
strcpy(inputp2, strtok(NULL, " ,-"));
Also I would like it to count up for every single time so that the first time it ran the for function it would do
strcpy(inputp2, strtok(NULL, " ,-"));
and the second time
strcpy(inputp3, strtok(NULL, " ,-"));
ect.
Ex: I input 10 20 30
input and inputp1 come out as 10
inputp2 comes out as 20
inputp3 comes out as 30
Upvotes: 1
Views: 86
Reputation: 84579
If I understand what you are needing, you can use a single statically declared array to hold the input as well as each separated token. You can duplicate the first token in the first element (holding the original input string) by virtue of the modification to the string by strtok
itself. For example:
#include <stdio.h>
#include <string.h>
enum { MAX_NAME = 5, MAX_NAME_SZ = 132 };
int main (void) {
size_t i, count = 0;
char *delim = " .,-\t\n";
char input[MAX_NAME][MAX_NAME_SZ] = { "" };
char *p = NULL;
if (!fgets (input[count++], MAX_NAME_SZ, stdin)) {
fprintf (stderr, "error: invalid input.\n");
return 1;
}
for (p = strtok (input[0], delim);
p && count < MAX_NAME;
p = strtok (NULL, delim), count++) {
strcpy (input[count], p);
}
for (i = 0; i < count; i++)
printf ("input[%zu] : %s\n", i, input[i]);
return 0;
}
Since strtok
adds a nul-terminating character in the original string after each token, input[0]
is automatically terminated after the first token.
Example Use/Output
$ ./bin/strtok_input
10 20 30
input[0] : 10
input[1] : 10
input[2] : 20
input[3] : 30
If I didn't understand what you were attempting to accomplish, let me know, otherwise, let me know if you have any questions.
Upvotes: 1