after i get a string from the user, how can i break the string into words??
likes
the string" i am very happy today."
to
i
am
very
happy
today
Printable View
after i get a string from the user, how can i break the string into words??
likes
the string" i am very happy today."
to
i
am
very
happy
today
If you don't require soemthing reentrant, strtok is a standard function:
If you do need a reentrant function, you'll have to write it yourself or use a nonstandard extension if your compiler supports one.Code:#include <stdio.h>
#include <string.h>
#define DELIM " "
int main(void)
{
char buff[BUFSIZ];
printf("Enter a string: ");
fflush(stdout);
if (fgets(buff, sizeof buff, stdin) != NULL) {
char *sep = strtok(buff, DELIM);
while (sep != NULL) {
puts(sep);
sep = strtok(NULL, DELIM);
}
}
return 0;
}
sorry, i havent typed it down that the string is stored in the 2D array having a maximum 80 words....
>sorry, i havent typed it down that the string is stored in the 2D array having a maximum 80 words....
So copy each token into the array. Something like this:
Code:#include <stdio.h>
#include <string.h>
#define DELIM " "
#define MAXWORD 80
#define MAXLEN 20
int main(void)
{
char words[MAXWORD][MAXLEN];
char buff[BUFSIZ];
int ntokens = 0;
int i;
printf("Enter a string: ");
fflush(stdout);
if (fgets(buff, sizeof buff, stdin) != NULL) {
char *sep = strtok(buff, DELIM);
while (sep != NULL) {
strcpy(words[ntokens++], sep);
sep = strtok(NULL, DELIM);
}
}
for (i = 0; i < ntokens; i++)
puts(words[i]);
return 0;
}
THx u very much
by the way
i am a beginner of c, many times find many difficulty in writing programs, how can i improve my programming skills?
>how can i improve my programming skills?
Read lots of good code and try to imitate what you read. Eventually you'll find yourself writing good code with ease.
>how can i improve my programming skills?
Taking an English course would also help.