I have this code in C, where I will be inputting a string of numbers separated by spaces, and splitting it with strsep. If I input a string like "1 2", and set strcmp to look for a number before the last element, the code works, but if I set strcmp to look for the last element, the code fails. Can you suggest any fixes?
char *string = malloc(1028), *found;
if (fgets(string, 1028, stdin) != NULL) {
while ((found = strsep(&string, " ")) != NULL) {
if (strcmp(found, "2") == 0) {
printf("%s\n", found);
}
}
}
It's because the last element that
foundpoints to is including the new line character. So you'd either have to add the new line tostrcmplike so:strcmp(found, "2\n")(assuming 2 was your last element) or when you callstrsepyou need to tokenize on both the space and new line character:strsep(&string, " \n").Complete solution:
A few things to observe: The
stringpointer is modified by thestrsepfunction so I've updated the code to use an intermediate variablep. I've also updated the code to validate the allocation was successful and then free it at the end. Depending upon your system requirements, you could consider forgoing the heap and allocatingstringon the stack.