c - How can I stop scanf-ing input after a certain character? -
i'm working on function takes filepaths , dices them smaller sections.
for example, if input parameter "cd mypath/mystuff/stack/overflow/string", want able return "cd" "mypath", "mystuff", "stack", "overflow", , "string" in succession.
while continually use "getchar", appending results ever-increasing string, stopping when getchar returns '/', feel there must more elegant way achieve same functionality.
any ideas?
you can use char * strtok ( char * str, const char * delimiters );
using /
separator.
an example here: http://www.cplusplus.com/reference/clibrary/cstring/strtok/
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "usage: %s path\n", argv[0]); exit(exit_failure); } char* saveptr = null; (char* str = argv[1]; ; str = null) { char *token = strtok_r(str, "/", &saveptr); if (token == null) break; printf("%s\n", token); } return 0; }
example
clang -wall *.c && ./a.out mypath/mystuff/stack/overflow/string mypath mystuff stack overflow string
Comments
Post a Comment