I have a string with the following format:
start 123
I am parsing it that way:
if (strstr(line, "start") == line) {
int number = -1;
if (sscanf(line + strlen("start "), "%d", &number) == 1) {
printf("start %d\n", number);
}
}
Is there any better way in C?
yes you can use only this:
if (sscanf(line, "start %d", &number ) == 1) {
no need for
if (strstr(line, "start") == line) {
any more
If you want to check more: Check that there is no extra characters after the number , then you can use the following format:
char c;
if (sscanf(line, "start %d%c", &number, &c) == 1) {
Note: the above formats (and even yours) do not check that there is only 1 space between "start" and the number. so if your string is something like "start \t 45" then the if will return true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With