Compare strings with sscanf, but ignore spaces
Use "%n"
to record where the scan stopped.
Add a formatted space where WS is to input
be ignored.
int n = -1;
sscanf( input, " drop all %n", &n);
// v---- Did scanning reach the end of the format?
// | v---- Was there additional text in `input`?
if (n >= 0 && input[n] == '\0') Success();
source to share
Instead of dealing with dirty data, it is often better to clean it up and then work with it. Cleanup only needs to be done once, whereas dirty data adds complexity to the code every time you have to use it. This step is often referred to as "normalization". Normalize entry to canonical form before use.
Clean up the input by trimming the whitespace and performing any other normalization (such as bending and normalizing internal whitespace).
You can write your own trim function, but I would recommend using a pre-existing function like Gnome Lib's g_strstrip () . Gnome Lib offers all kinds of handy features.
#include <glib.h>
void normalize_cmd( char *str ) {
g_strstrip(str);
// Any other normalization you might want to do, like
// folding multiple spaces or changing a hard tab to
// a space.
}
Then you can use strcmp
on the normalized input.
// This isn't strictly necessary, but it nice to keep a copy
// of the original around for error messages and such.
char *cmd = g_strdup(input);
normalize_cmd(cmd);
if ( strcmp(cmd, "drop all") == 0) {
puts("yes");
}
else {
puts("no");
}
Putting all normalization up reduces the complexity of any subsequent code that needs to work with that input; they don't have to keep repeating the same concerns about dirty data. By putting all the normalization in one place, and not scattered throughout the code, you are sure that it is consistent and the normalization method can be constantly updated.
source to share