I am trying to tokenize a sentence that starts with spaces but I get segmentation fault. I am trying to skip the spaces and store the words. Is there an alternative built-in function to achieve this?
#include <string.h>
#include <stdio.h>
[...]
char *buff = " push me", *token;
token = strtok(buff, " \n");
while (token) {
printf("%s", token);
token = strtok(NULL, " \n");
}
[...]
CodePudding user response:
change to this
char buff[100], *token;
strcpy(buff," push me");
Before you were pointing to a string constant with the buff variable. The compiler will put this in a segment that is read only. If you try to write to that segment you get a segmentation fault. So in the code above we allocate space in read/write memory to store the string and then copy it in.
CodePudding user response:
buff
points to a string literal that usually cannot be modified.
strspn
and strcspn
can be used to parse the sub-strings.
#include <stdio.h>
#include <string.h>
int main ( void) {
char *buff = " push me";
char *token = buff;
size_t span = 0;
if ( ! buff) {
return 1;
}
while ( *token) {
token = strspn ( token, " \r\n\t\f\v"); // count past whitespace
span = strcspn ( token, " \r\n\t\f\v"); // count non-whitespace
if ( span) {
printf ( "%.*s\n", (int)span, token); // precision field to print token
}
token = span; // advance token pointer
}
}
CodePudding user response:
strtok()
, like others, are "library functions", not "built-in".
Very intelligent people wrote these functions expecting they would be used in clean, elegant and terse ways. I believe this is what you want:
#include <stdio.h>
#include <string.h>
int main() {
char buf[] = " push me"; // don't point at a "string literal'
for( char *tok = buf; (tok = strtok( tok, " \n") ) != NULL; tok = NULL )
printf( "%s\n", tok ); // added '\n' for clarity
return 0;
}
Output
push
me