if for instance i have a string: Hi:my:name:is:lacrosse1991: how could I use strtok to retrieve just the is (in other words the fourth field)? This would be similar to how you would use cut in bash, where i would just do cut -d ":" -f 4. If this is the wrong function to be doing such a thing, please let me know, any help is much appreciated, thanks! (I’ve just recently started teaching myself C, I apologize ahead of time if these are obvious questions that i am asking)
here is an example of the cut command that I would use
x=$(echo "$death" | cut -d ':' -f 4)
y=$(echo "$death" | cut -d ':' -f 5)
z=$(echo "$death" | cut -d ':' -f 6)
I’d avoid
strtokfor this purpose (and most others, for that matter). Under the circumstances, I think I’d just usesscanfwith ascansetconversion:In this, we start by repeating
%*[^:]:three times. Each of these reads a string including any characters except a colon, then a colon. The*means that should be read from the input, but ignored (not assigned to anything). Then, for the fourth field we have the same thing, except we do not include the*, so that field does get assigned, in this case tofield_four(though you should obviously use a more meaningful name).For the fourth field, I’ve also added a specification of the maximum length. Since
sscanfalways includes a\0to terminate the string, but doesn’t include it in the count, we need to specify a size one smaller than the size of the buffer.